1

I'm building an app where a "slice reducer" needs to access state of another "slice reducer". The redux docs talks about using a custom combine reducer in order to pass in the root state to the reducer - Beyond combineReducers

Thus far, I have this for my root reducer:

import cats from '../slices/cats'
import dogs from '../slices/dogs'
import status from '../slices/status'

function combinedReducer(state = {}, action) {
  return {
    status: status(state.status, action),
    dogs: dogs(state.dogs, action),
    cats: cats(state.cats, action, state),
  };
}

 export default configureStore({ reducer: combinedReducer });

I don't seem to be able to get the root state for my cats reducer - passed in as the 3rd arg above.

const assetsSlice = createSlice({


name: 'cats',
  initialState,
  reducers: {
    setFetched: (state, { payload }, root) => {
      // root is undefined
      state.type = payload + root.dogs.legs;
    },
  },
});

This should work, no?

If I use a vanilla reducer that's not created by createSlice I am able to get the root state

export default (state = initialState, action, root) => {
// root - { status: {}, dogs: {}, cats: {} }
};
zootpera
  • 11
  • 1

1 Answers1

2

This is not possible as a third argument since RTK's reducers only pass the first two arguments to the case reducers.

You could just add it to the action though (but granted, that's hacky):

function combinedReducer(state = {}, action) {
  const actionWithFullState = { ...action, meta: {...action.meta, fullState: state }}
  return {
    status: status(state.status, action),
    dogs: dogs(state.dogs, action),
    cats: cats(state.cats, actionWithFullState),
  };
}
phry
  • 35,762
  • 5
  • 67
  • 81
  • 2
    Yea I thought about it, but due to the hacky nature I didn't want to pursue it. I ended up listening in on the actions of the other "slice reducer" by using the `extraReducers` and updating the "slice reducer" I'm working with – zootpera May 12 '21 at 18:10
  • That sounds definitely like the cleaner solution :) – phry May 12 '21 at 18:25