0

I initially had my reducer as such, and it does not work (my updated redux state does not lead my component to update, my component's prop 'RecipeStore' is mapped onto the redux state's 'myRecipes' property)

const initialState={
    myRecipes: []
}

export default function(state=initialState, action){
    switch(action.type){
        case SUBMIT_RECIPE:
            
            const newState={...state}
            newState.myRecipes.push(action.payload)
            return newState
        default:
            return state;}}

I figured that my component did not rerender with redux store update because I mutated state, and you should never mutate state. So I rewrote the reducer as such:

const initialState={
    myRecipes: []
}

export default function(state=initialState, action){
    switch(action.type){
        case SUBMIT_RECIPE:
            console.log("reducer invoked")
            const copyState={...state, myRecipes:state.myRecipes.concat(action.payload)}
            return copyState
        default:
            return state;
    }
}

And this time it worked - my component updates every time the redux store changes. However - my original reducer also created a copy of the original state using the spread operator, and only mutated the copy, why doesn't it work?

This is one of these situations where I'm glad that I solved the problem but am peeved that I don't know why.

Can someone lend me their thought?

Iggee Xy
  • 83
  • 1
  • 8
  • In you first example you've created a copy of the `state` but this actually creates a shallow copy of the state. That means the top level of the state is deeply copied but the `myRecipes` array is not. For more - https://stackoverflow.com/a/61422332/4610740 – Sajeeb Ahamed Apr 11 '22 at 16:56
  • I guess in the first example you only recreated the object but the array that is referenced in the object was not recreated. Array reference did not change so there was no rerender. – Pinka Apr 11 '22 at 16:57
  • Thank you! I learned about spread operator only deep copying the first-layer of the object. But didn't think this connected to my problem. I will check out the link. – Iggee Xy Apr 11 '22 at 17:03
  • The better way to express this is: `return { ...state, myRecipies: [ ...state.myRecipies, action.payload] }` – Chad S. Apr 11 '22 at 18:09

0 Answers0