Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react - "Reducers may not dispatch actions." after navigating to a route

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?

like image 861
user1326293 Avatar asked Dec 22 '16 14:12

user1326293


People also ask

Can we dispatch actions from reducers?

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.

What is the difference between actions and reducers redux?

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.


2 Answers

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

like image 114
T Mitchell Avatar answered Oct 09 '22 13:10

T Mitchell


not the best solution but it works. inside reducer

  setTimeout(()=>{
           store.dispatch(
               //
             )
       },1);
like image 1
Anish Avatar answered Oct 09 '22 14:10

Anish