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.