Reputation: 1186
I am trying to update the state using React Hooks. I have an array of objects, within an object is another array I am trying to update. All these are generated dynamically.
[
{
"question": 2,
"choices": ["Heart Disease", "GERD", "ASTMA"]
},
{
"question": 4,
"choices": ["Heart Disease", "GERD", "ASTMA"]
},
{
"question": 9,
"choices": ["Heart Disease", "GERD", "ASTMA"]
}
]
My state looks like this. I am creating a form that contains multiple choices for different questions on the same page. So if I am on question 2, I want to be able to add (or remove) to the choices on that question.
How can I do this using useState
?
Upvotes: 1
Views: 53
Reputation: 13682
In order to update the nested state, you need to map over the state and update the specific question id.
Here is the code for adding and removing choices.
let initialState = [
{
"question": 2,
"choices": ["Heart Disease", "GERD", "ASTMA"]
},
{
"question": 4,
"choices": ["Heart Disease", "GERD", "ASTMA"]
},
{
"question": 9,
"choices": ["Heart Disease", "GERD", "ASTMA"]
}
];
const [questions, setQuestions] = React.useState(initialState);
const addChoice = (questionId, choice) => {
setQuestions(question.map(q => {
if(q.question === questionId){
return {...q, choices: [...q.choices, choice]}
}
return q;
}))
};
const removeChoice = (questionId, choice) => {
setQuestions(question.map(q => {
if(q.question === questionId){
return {...q, choices: q.choices.filter(c => c !== choice)}
}
return q;
}))
};
Upvotes: 1
Reputation: 11687
In case you meant that you need to change the choices based on the question number dynamically. Then maybe below should do the job. It is written on the fly and not tested.
const [questions, setQuestions] = React.useState(defaultObject);
function questionSelected(questionNumber) {
const temp = questions;
const question = temp.find(n => n.question == questionNumber);
question.choices = ['New', 'Choices'];
setQuestions([...temp]);
}
Hope it helps.
Upvotes: 0