Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you replace entire state in Redux Toolkit reducer?

EDIT: The solution is to return state after I replace it completely (return state = {...action.payload})! But why? I don't need to return it when I replace the fields individually.

I'm working with the Redux Toolkit, which simplifies some Redux boilerplate. One thing they do is use Immer to allow you to directly 'modify' state (in fact, you're not). It works fine, except I don't know how to replace my section of state entirely. For instance, I want to do something like this

const reducer = createReducer({ s: '', blip: [] }, {

    [postsBogus.type]: (state, action) => {
        state = { ...action.payload };
    }

but state remains untouched. Instead I have to do this

[postsBogus.type]: (state, action) => {
    state.s = action.payload.s;
    state.blip = action.payload.blip;
}

Is there a way I can replace state entirely?

like image 815
Cerulean Avatar asked Jan 31 '20 11:01

Cerulean


People also ask

How do I change my state in Redux Reducer?

The only way to update a state inside a store is to dispatch an action and define a reducer function to perform tasks based on the given actions. Once dispatched, the action goes inside the reducer functions which performs the tasks and return the updated state to the store. This is what Redux is all about.

Can I mutate state in Redux toolkit?

One of the primary rules of Redux is that our reducers are never allowed to mutate the original / current state values!

Can we update state in reducer?

The state is updated and managed by reducers. Reducers always have to return something even if it's null ; they should never return undefined . If a reducer's state is an object, you must always return a new object instead of editing the object in place.

Will Redux toolkit replace Redux?

There is no difference between using Redux or Redux Toolkit in regards to React. That is the separate react-redux package you have to use in both cases. The difference between the two is the amount and safety of non-React-related code. thanks, @phry and hyetigran for the correction.


1 Answers

Yes, as you noted, you must return a new value to replace the state entirely.

Even in a "plain" Redux reducer, assigning state = newValue does nothing, because all that does is say that the local function variable named state is now pointing to a different value in memory. That does nothing to return a new value.

For Immer specifically, you can either mutate the contents of the Proxy-wrapped state value as long as it's an object or array, or you can return an entirely new value, but not both at once.

like image 96
markerikson Avatar answered Sep 28 '22 06:09

markerikson