Issue
const initState = {
questions:[
{
id: uuidv4(),
answers:[
{answerid: uuidv4()},
{answerid: uuidv4()}
]
},
],
}
this is the state i wanna function to add object in the answers array so the state will be after add like that:
const initState = {
questions:[
{
id: uuidv4(),
answers:[
{answerid: uuidv4()},
{answerid: uuidv4()},
{answerid: uuidv4()}
]
},
],
}
Solution
you can use a library like Immer for deeply nested objects update,
My try as below
const initState = {
questions: [
{
id: 1,
answers: [
{
answerid: 34,
},
{
answerid: 12,
},
],
},
],
};
const newState = {
...initState,
questions: initState.questions.map((q) => {
const newq = {
...q,
answers: [
...q.answers,
{
a: "b",
},
],
};
return newq;
}),
};
newState.questions[0].id = 2; // to test it doesn't mutate original object
console.log({initState, newState});
Answered By - KcH
Answer Checked By - - Mary Flores (ReactFix Volunteer)