Home > Mobile >  react - setState child property (complicated hierarchy - two maps)
react - setState child property (complicated hierarchy - two maps)

Time:09-04

I have this onChange from a different question I asked. Its a property, in an object, in a array, in an object:

onChange={(e) => setQuiz({ ...quiz, questions: quiz.questions.map((child, index) => index === selectedQuestion ? { ...child, question: e.target.value } : child) })} />

But now I want to edit a property, in an object, in an array, in an object, in an array, in an object like this V

object (quiz):{
      arr (questions):[
            object (question):{
                arr (answers):[
                    object (answer):{
                                   property (content) <<<<<<<
                                 }
                         ]
               }
        ]
}

This is what I have so far but I get error on syntax:

onChange={(e) => 
   setQuiz({ ...quiz, questions: 
        quiz.questions.map((child, index) => index === selectedQuestion ? { 
             child.map((answer, x)) => x === selectedAnswer ? {
                 ...child, content: e.target.value } : child)  }
             : child) 
   })
} />

enter image description here

error:

[0m [90m 26 |[39m                         setQuiz({ [33m...[39mquiz[33m,[39m questions[33m:[39m [0m
[0m [90m 27 |[39m                             quiz[33m.[39mquestions[33m.[39mmap((child[33m,[39m index) [33m=>[39m index [33m===[39m selectedQuestion [33m?[39m [0m
[0m[31m[1m>[22m[39m[90m 28 |[39m                                 { child[33m.[39mmap((answer[33m,[39m x)) [33m=>[39m x [33m===[39m selectedAnswer [33m?[39m [0m
[0m [90m    |[39m                                        [31m[1m^[22m[39m[0m
[0m [90m 29 |[39m                                     {[33m...[39mchild[33m,[39m content[33m:[39m e[33m.[39mtarget[33m.[39mvalue } [33m:[39m child)  }[0m
[0m [90m 30 |[39m                                     [33m:[39m child) })} [33m/[39m[33m>[39m[0m
[0m [90m 31 |[39m                 [33m<[39m[33m/[39m[33mdiv[39m[33m>[39m[0m

Live demo: https://codesandbox.io/s/vigilant-driscoll-2pgwvh?file=/src/App.js

CodePudding user response:

You try to map an object (child is an object), you can try this to solve your problem:

setQuiz({
    ...quiz,
    questions: quiz.questions.map((question, index) => {
        if (index === selectedQuestion) {
            return {
                ...question,
                answers: question.answers.map((answer, index) => {
                    if (index === selectedAnswer) {
                        return {
                            ...answer,
                            content: e.target.value
                        };
                    }
                    return answer;
                })
            };
        }
        return question;
    })
})

  • Related