Update Object with an array using React States

I have a state quiz and another one questionList and the following quiz structure is like this:

const [quiz, setQuiz] = useState({
        title: 'test',
        description: 'test',
        user_id: 'test',
        thumbnail: 'test',
        timer: 'test',
        question: []
    })

And somehow the structure of questionList is:

[{
   id: Math.floor(100000 + Math.random() * 900000),
   question: "data",
   answer1: "data",
   answer2: "data",
   answer3: "data",
   answer4: "data"
},
{
   id: Math.floor(100000 + Math.random() * 900000),
   question: "data",
   answer1: "data",
   answer2: "data",
   answer3: "data",
   answer4: "data"
}
]

So with a function, I’m filling the questionList but what I want to do is also beside that update (or replace) the question: [] with the new array from the questionList in the quiz state.

Here is how I add a question in the List:

const addQuestion = (question) => {
   setQuestionList([...questionList, question]);   
   // here the logic to update the property question on Quiz state with the new added object into questionList
};

So when a question is added to the list, that list array I want to update to questions: [], as an update, and not add another field.

>Solution :

you can do this in your function,
replace your old function,

const addQuestion = (question) => {
   setQuestionList([...questionList, question]); 
};

to this, this will work

const addQuestion = (question) => {
   setQuestionList([...questionList, question]);   
   setQuiz({...quiz, question: [...questionList, question]})
};

Leave a Reply