Home > Mobile >  Replace state of multiple slices using redux toolkit
Replace state of multiple slices using redux toolkit

Time:10-20

How could you replace the state of a store consisting of multiple slices with some other, new state in react using redux toolkit?

You can revert the whole store to its initial state using extraReducers: could the same mechanism be used to change the store state to something else then the initial state?

For example, you would have something like this:

const aSlice = createSlice({ 
  name: 'a', 
  initialState: {a: 1}, 
  reducers: {
    someReducer(state, action) {...}
  }
})
const bSlice = createSlice({ 
  name: 'b', 
  initialState: {b: 'foo'}, 
  reducers: {}
})

const store = configureStore({
  reducer: {
    aReducer: aSlice.reducer,
    bReducer: bSlice.reducer,
  }
});

export type RootState = ReturnType<typeof store.getState>

In a react component you can update the state with:

const dispatch = useDispatch();
dispatch(someReducer({...}));

How would you replace the state of the whole store with something like this:

{
  "aReducer": {"a": 2},
  "bReducer": {"b": "bar"},
}

CodePudding user response:

You can use extraReducer for that.

You can pass an arbitrary payload (like {"a": 2, "b": "bar"} to the created action. With createAction you can have actions which don't "belong" to a specific slice, see: https://redux-toolkit.js.org/api/createAction and implement extraReducers in both slices which only use their part of the payload.

CodePudding user response:

Reducers, by definition, only have access to the section of state that they own. So, if I have {users: usersReducer, posts: postsReducer}, the usersReducer has no access to the posts state slice at all. How can I access state of another slice in redux with redux-toolkit?.

So you have to dispatch two actions of two slices and every individual reducer will update its state individually.

  • Related