How can I setState for array with nested objects with arrays?

Viewed 35

How can I change the value object inside my array with objects using setState? How I have it right now it only add value to the first array I tried mapping all the way down to value but its not working. Any advice would be great. And one more question. I have an handleClick(event) that targets the id in my child component. How would you write a function to change the value in the the state using setState.

React.useEffect(()=> {
      if(start === true){
        
      fetch("https://opentdb.com/api.php?amount=5&category=27&difficulty=easy&type=multiple")
      .then(res => res.json())
      
      .then(data => setState(data.results.map(item =>
      ({selectedQuestion: "",
          buttons: item.incorrect_answers.concat(item.correct_answer).map(item => 
            ({use: item, value: false, id: uuidv4()})),
          questions: item.question   
          
      }))))
    }} , [start])
  function startGame () {  
    setStart(prevState => !prevState)
}
const myButtons = state.map(function(item) { 
  return (<Quiz 
  key={uuidv4()}
  buttons={item.buttons}
  question = {item.questions}
  handleClick ={(event) =>handleClick(event.target.id)}

/> ) })
  console.log(state)
    let myFlat = state.map(item => item.buttons.map(item => item.id))
    let finalFlat = myFlat.flat()
    
  function handleClick (event) {
    for(let i = 0; i<finalFlat.length; i++){
if(finalFlat[i] === event){
  setState(item => item.map(item =>({
    ...item, value:true
  })))
}}}
1 Answers

You can use Object.assign to replace only parts of an map:

> obj = {"arr1": [1,2,3], "arr2": [9]}
{ arr1: [ 1, 2, 3 ], arr2: [ 9 ] }

> Object.assign(obj, {"arr1": [1,2,3,4]})
{ arr1: [ 1, 2, 3, 4 ], arr2: [ 9 ] }

Also, In react you shoud use setState to change state.

Related