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

120
Visualizações
JavaScript strange behavour on object assignment

I am currently writing a Redux reducer and I am facing an issue with the state update.

The code bellow is supposed to toggle an open state. The problem is that the resulting state does not return the same value depending on how one accesses it.

case actionTypes.toggle: {
         let newState = {...state}
         newState.questions[action.questionNumber].open = !state.questions[action.questionNumber].open
         console.log("newState open", newState.questions[action.questionNumber].open)
         console.log("question number", action.questionNumber)
         console.log("new state questions", newState.questions)
         console.log("new state", newState)
         return newState
       }

The strange part is that the console output reads:

newState open true
question number 0
new state questions [list of questions with questions[0].open == true]
new state [contains a list of questions with questions[0].open == false]

In short the final newState does not contain the updated questions[0] while newState.questions[0] does.

To make it even more confusing one can replace line 3 with:

newState.questions[action.questionNumber].open = true

and now everything works as expected.

I am completely lost on how such a behavior can even be triggered. Any hint to solve the problem is appreciated.

Thank you in advance.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You unfortunately are not treating state as immutable. This line...

newState.questions[action.questionNumber]

references the same array and object within it as what exists in the original state. This...

let newState = {...state}

only creates a shallow copy.

My advice would be to use something like this

// break the reference to the "questions" array
const questions = [...state.questions]
const question = questions[action.questionNumber]

// Remove the selected index and replace with a new value
questions.splice(action.questionNumber, 1, {
  ...question,
  open: !question.open
})

return {
  ...state,
  questions
}
about 4 years ago · Juan Pablo Isaza Relatório

0

@Phil has a great answer.

But just to add (since not suitable as comment), you can use ES6 too to map the results.

//Rebuild the array
const questions = state.questions.map((q,i) => {
  if(i === action.questionNumber) {
     return {...q, open:!q.open};
  } else {
     return q;
  }
})

//can be written as questions or questions:questions
return {
  ...state,
  questions: questions
}
about 4 years ago · Juan Pablo Isaza Relatório
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