0

I don't know why my map is not re-rendering, even if the state is updated.

  const [newFaq, setNewFaq] = React.useState(questionReponse)

  const addQuestion = () => {
    newFaq.push({id: newFaq.length+1, question: "", reponse: ""})
    setNewFaq(newFaq)
    console.log(newFaq)

  }

  return (
    <div className="main">
        <div className="block">
          { 
            newFaq.map((el, index) => {
              return (<QuestionModif key={el.id} id={index} question={el.question} reponse={el.reponse} onGetValues={handleSubmit}/>)
            }
            )
          }
        </div>
    </div>
  );
};
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • you should not do anything with newFaq other than read it - if you need to update it use the setNewFaq. get rid of `newFaq.push({id: newFaq.length+1, question: "", reponse: ""})` and use setNewFaq. – Yesthe Cia Jul 25 '22 at 08:43

2 Answers2

0

This is because ur passing the same array to setNewFaq, u need to pass a new array.

We can use the spread syntax.

setNewFaq([...newFaq, {id: newFaq.length+1, question: "", reponse: ""} ])
Pierre
  • 432
  • 1
  • 7
0

Please never mutate this.state directly,

More information about this situation;

checkout