I'm using
hashHistory.push('/home')
To navigate to some route on my app. However, whenever I use it I get
Reducers may not dispatch actions.
How can I properly navigate to some route without getting this error?
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
Reducers: As we already know, actions only tell what to do, but they don't tell how to do, so reducers are the pure functions that take the current state and action and return the new state and tell the store how to do.
Assuming you are using Redux, you can use the thunk middleware and react-router-redux
https://github.com/gaearon/redux-thunk
https://github.com/reactjs/react-router-redux
This will allow you to dispatch an action, reduce it and then dispatch another action afterwards
import { push } from 'react-router-redux'
const someAction = (somePayload) => (dispatch, getState) => {
dispatch({
type: 'SOME_ACTION',
payload: {
somePayload
}
});
// Get the updated state from the store and navigate
let { someVar } = getState();
if (someVar === 'some value') {
dispatch(push('/home'));
}
};
// Call like so
store.dispatch(someAction())
If you're not using redux or don't want to go that route, make sure you are not dispatching an action inside a reducer or part of that action cycle
not the best solution but it works. inside reducer
setTimeout(()=>{
store.dispatch(
//
)
},1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With