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?
2
Answers
The problem seems to come from here
Using the setter function of a state is not synchronous, meaning that
content
will not be already equal toresponse.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
The first issue is in your axios then clause.
useEffect
You have a couple of ways to simulate this scenario. Even without a useEffect.
since you are using React-Router:
you could return a navigate component instead of listening to a change.
Toggle
The problem you see here is that a toggle hook is a quick and dirty way to "toggle" stuff, however, this also means you can only do that and the rise grows to create another approach
When you close your modal, you could use the onClose action to simulate what you want.
You could update the onClose to simply navigate
Either way, I would drop the useEffect.