Updating State in nested objects in Arrays

Viewed 28

Im learning React at the moment and I´m running into an Problem Right now I´m working on a little Quiz app. The questions and answers are from an API.

State

const [questions, setQuestions] = React.useState([])

This is how the state Object looks like

[{question: "Qeustion1?", 
answers: [
{value: "answer1", selected: false, id: 1}, 
{value: "answer2", selected: false, id: 2}, 
{value: "answer3", selected: false, id: 3},
{value: "answer4", selected: false, id: 4}]
}]

I want to change the selected property to true, if the clicked field ID matches with state ID so I can change the color for the selected answer field. But somehow I will always get an Error when trying to change the property.

    function selectAnswer(id) {
        setQuestions(prev => {
            prev.forEach(element => {
                element.answers.map(answer => {
                    return id === answer.id ? {...answer, selected: !answer.selected} : answer
                })
            })
        })
} 

UPDAT ERRO MSG Error: Unknown error (/node_modules/react-dom/cjs/react-dom.development.js:237)

Maybe there is someone who can help me out.

1 Answers

If you are using function form of state update, it should return the new state value Eg. setCount(count=>count+1) or more explicitly setCount(count=>{ return count+1})

Your state updating function never gets a return value

Also the forEach method does not return a new array. replace forEach implementation with map

You will run into more problems if everytime the four options for every question in your questions array always has id 1,2,3,4. You will also have to identify which question is currently being answered.

Related