I lately noticed that calling useSelector in a react-redux is a bit delayed.
Now i am using useEffect to check if the state is a certain value. like so:
const user= useSelector(state=>state.user.value);
useEffect(()=>{
if (!user){
alert('You have to login to see this page');
//Redirect the visitor to the login page
}
},[]);
I noticed that useEffect runs before useSelector fetch the data from the state and finds the user null so it displayes the message and redirects the user while I have a user in the state. By the way I am also using redux-persist middle-ware to store the state in the localStorage
I tried to delay the logic inside useEffect like so:
useEffect(()=>{
setTimeout(() => {
if (!user){
alert('You have to login to see this page');
//Redirect the visitor to the login page
}
},10000);
},[]);
But still it does not work as it takes the same null user that it came with in the the beginning of loading the page!!
I put this code to watch the user change:
useEffect(() => {
console.log('At: ' + new Date(Date.now()).toLocaleString().split(',')[1] + ' user is:', user);
}, [user]);
And this is a screen shot of the console:

Any hints on how to bypass this problem? Or may be I am doing something wrong?