Phil
Phil

Reputation: 23

How to access a reducer state within another reducer when we use "redux-starter-kit"?

Now I made two reducers (student reducer and exam reducer) using redux-starter-kit. How can we access the state of exam reducer in student reducer? Also, can we call dispatch function of exam in student reducer to modify the state of exam state?

examReducer.js

const exam = createSlice({
 initialState: {
   mathScore: 0
 },
 reducer: {
   setMathScore: (state, action) => {
    state.mathScore = action.payload;
   }
 }
});

studentReducer.js

const student = createSlice({
 initialState: {
   pass: false
 },
 reducer: {
   setMathScore: (state, action) => {
    //try to get math score from exam reducer
    state.pass = /*TODO*/ > 70 ? true : false;
   }
 }
});

store.js

const store = configureStore({
  reducer: {
    exam: exam.reducer,
    student: student.reducer
  }
});

Upvotes: 2

Views: 1610

Answers (1)

markerikson
markerikson

Reputation: 67469

You can't "access state of another reducer", because that's not how Redux is meant to work in general. There's nothing special about Redux Starter Kit in this regard.

Per the Redux FAQ entry on "sharing state between reducers":

Many users later want to try to share data between two reducers, but find that combineReducers does not allow them to do so. There are several approaches that can be used:

  • If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
  • You may need to write some custom functions for handling some of these actions. This may require replacing combineReducers with your own top-level reducer function. You can also use a utility such as reduce-reducers to run combineReducers to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.
  • Async action creators such as redux-thunk have access to the entire state through getState(). An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.

Also, you definitely cannot dispatch actions inside a reducer. This is forbidden, and will throw an error.

Upvotes: 1

Related Questions