Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]})
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading