• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

385
Views
Two ways of updating an array in redux state object, why does one work and the other doesn't?

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?

about 3 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error