I have a authState (is a boolean), it tells you if the user isLogged or it doesn’t. I have a main layout that I share with all my components. It has this logic in the useEffect
const isLogged = useSelector(selectAuthState);
const router = useRouter();
useEffect(() => {
if (isLogged) {
router.push('/')
}else{
router.push('/login')
}
}, [isLogged])
The problem is that the default value of the selectAuthState is false, so the first render it value is false (even if in the localStorage the real value of the authState is true), in the second render the real value comes (it’s true), so my app get redirects to the ‘/’ route always because the default value of the authState is false. How can I check if the redux store ‘is ready’ or whatever I need to be sure that I have the actual redux state?
2
Answers
Try to add a check to see if the Redux state has been initialized before performing the redirection:
Redux is ready when the store is created, passed to the React-Redux
Provider
component, and the app is mounted and rendered. There’s not really anything to check.The problem is that you are using initial
isLogged
state that matches the unauthenticated user. It is often the case that being authenticated isn’t simply a binary function, but actually a trinary function, e.g. authenticated, unauthenticated, and unknown. You should start from the unknown state if you haven’t any way to initialize the state to one of the other to "confirmed" states.You mentioned that you have some auth state in localStorage. You may be able to initialize the state from localStorage. If there is nothing already stored then
null
is returned, so you’ll still want the above component logic to handle the UI.Example: