How to run useState asynchronously
Solution 1:
There are couple of ways you can achieve this. i am posting the useEffect
way.
you can use useEffect
and listen on the isLogin
if it changes trigger the setisLogin()
function.
code
const Navbar = () => {
const [isModalOpen, setisModalOpen] = useState(true)
const [isLogin, setisLogin] = useState(true)
React.useEffect(() => {
if(!isLogin){
setisLogin(true);
}
},[isModalOpen])
const onClose = () =>{
setisModalOpen(false)
}
return (<Modal isOpen={isModalOpen} onClose={() => onClose()} >
{!isLogin ?
<Register />
:
<Login setisLogin={() => setisLogin(false)} />
}
</Modal>)
}
useState and setState both are asynchronous in nature already.