useEffect triggers after second state change Reactjs

I want this useEffect to take me to another screen if those two values meet the conditions.

useEffect(() => {
    if(userAdded == true && isOpen== false){
      return navigate("/login");
    }
  },[userAdded, isOpen])`

I use setUserAdded if an axios call returns a specific response

axios.put("https:xxx", data, {
        headers: headers,
      })
      .then(function (response) {
        setContent(response.data);
        console.log(response.data);
       if (content.includes("agregado")){
          setUserAdded(true);
        }
        togglePopup(); /*I want the useEffect to take me to /login after I close this*/
        
      })

and isOpen is a state I use to control a popup component with togglePopup(). The navigate function works only after I open and close the popup a second time, then it takes me to /login.

Any ideas of what I might be doing wrong?

>Solution :

The problem seems to come from here

/** You set the value of `content`*/
setContent(response.data);

// ...

/** You the check the value of content directly after */
if (content.includes("agregado")){
 setUserAdded(true);
}

Using the setter function of a state is not synchronous, meaning that content will not be already equal to response.data when we enter the condition. But when you redo the action of opening and closing the popup, content will have the correct value from before, so it will work.

The best workaround is to remove the condition and put it in a use effect

useEffect(() => {
if (content?.includes("agregado")){
 setUserAdded(true);
}
}, [content])

Leave a Reply