Skip to content
Advertisement

React state update not working with setState

Okay so it’s simple

I have an array of answers inside an array of questions. the user has the option to select more than one answer.

When an answer is selected, the text should change to selected and unselected if it isn’t selected.

These are the steps i’ve tried to update my state

step 1 using map

JavaScript

step 2 using find

JavaScript

Well after using the sample logics above, none of them seem to work Thanks in advance

Advertisement

Answer

Issue

You are mutating the state in both cases. I’ll cover the first snippet.

JavaScript

The currentQuestion.answers object of the state.info.questions state was mutated and the state.info.questions array reference never changed so React isn’t “seeing” this as an update and isn’t triggering a rerender.

Solution

Apply the immutable update pattern. You must shallow copy all updates into new array and object references.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement