0

I need to update the store of my application using reducer. But I wanted to make it dynamic in a way that I need not to write different actions for updating the store at the same level.

Lets say below my store looks like this...

const store  = { nonPersistedState : {first :"", second : "", third : ""} }

all the first, second and third being on the same level of nonPersistedState.

Now for any of the above three if I want to update them, below is my action and reducer function

//action
dispatch({type: "UPDATE_MODEL", value : true, model : "first"}); /*model can be second or third as well*/


//store
    const initialState = {
        first :"", second : "", third : ""
    };

//reducer
    const nonPersistedState = (state = initialState, action) => {
        switch (action.type) {
            case 'UPDATE_MODEL':
                const localState = { ...state };
                localState[action.model] = action.value;
                return { ...localState };
            default:
                return state;
        }
    };

    export default nonPersistedState;

Now here I am creating a copy of the state first and then mutating it directly and then again returning the copy of the state.

So My question is, am I mutating the store or it is fine to do so? However I am not getting any warning or error message in the console and forms are getting re-rendered. Please provide inputs.

1 Answers1

1

The way you're doing it is correct. Using the spread operator to create the new state is even referenced in the Redux doc.

You could however slightly reduce the length of your code by assigning the new property directly at the same time you use the spread operator. It would look like this :

const nonPersistedState = (state = initialState, action) => {
    switch (action.type) {
        case 'UPDATE_MODEL':
            return {
                ...state,
                [action.model] : action.value
            };
        default:
            return state;
    }
};
Kewin Dousse
  • 3,314
  • 2
  • 22
  • 43