Next.js Discord

Discord Forum

react-hooks/exhaustive-deps

Answered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
I have this error message :
55:6 Warning: React Hook useEffect has a missing dependency: 'index'. Either include it or
remove the dependency array. You can also replace multiple useState variables with useReducer if 'setAnswersHistoric' needs the current value of 'index'. react-hooks/exhaustive-deps

But the problem is that if I put index in the dependencies it will break down the logic.
Answered by joulev
seems like you can just get rid of the entire newAnswer state
const handleContinueAction = (answer: string) => {
  if (answer) {
    setIndex((prevIndex) => Math.min(prevIndex + 1, exercices.length - 1));
    setAnswers((prevAnswers) => [...prevAnswers, answer]);
    setAnswersHistoric((prevAnswers) => {
      const updatedAnswers = [...prevAnswers]; // Crée une copie du tableau
      updatedAnswers[index - 1] = answer; // Met à jour l'élément à l'index spécifié
      return updatedAnswers; // Retourne le nouveau tableau mis à jour
    });
  }
};
View full answer

5 Replies

Sloth bearOP
@Sloth bear Click to see attachment
seems like you can just get rid of the entire newAnswer state
const handleContinueAction = (answer: string) => {
  if (answer) {
    setIndex((prevIndex) => Math.min(prevIndex + 1, exercices.length - 1));
    setAnswers((prevAnswers) => [...prevAnswers, answer]);
    setAnswersHistoric((prevAnswers) => {
      const updatedAnswers = [...prevAnswers]; // Crée une copie du tableau
      updatedAnswers[index - 1] = answer; // Met à jour l'élément à l'index spécifié
      return updatedAnswers; // Retourne le nouveau tableau mis à jour
    });
  }
};
Answer
see more: https://react.dev/learn/you-might-not-need-an-effect
in this case you are listening to changes in newAnswer to update some states based on the new newAnswer value. but... you could just remove the setNewAnswer and update the states directly in the event handler
Sloth bearOP
Ok Thanks
Yes it works thanks