lundi 4 janvier 2021

Logical error in React useEffect and conditional statement

I have recently asked a question about infinite loop caused by useState in React, and I got help. But now I have another bug with same code;

const [scoutMode, setScoutMode] = useState("");
const [bottomLinks, setBottomLinks] = useState([]);

useEffect(() => {

setScoutMode("weeklyProgramme");

if (scoutMode == "weeklyProgramme") {
  setBottomLinks(["x", "y"])
  console.log("weeklyprogramme");

} 
else if (scoutMode == "camp") {
  setBottomLinks(["a", "b"])
  console.log("camp");

} 

else {
  setBottomLinks(["c", "d"]);
  console.log("None")
}
console.log(bottomLinks);
}, [scoutMode])

I expected that it writes ["x", "y"] and "weeklyprogramme" in console because obviously the first condition is true, but instead the output is like this: picture of output

It looks like it runs partly the first condition's statements and also the else statement. Could somebody explain? Does React or hook work unexpectedly?

Aucun commentaire:

Enregistrer un commentaire