Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

466
Visualizações
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 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda