I am building simple authorization application. I am using MERN stack + Redux and basic logic is that after certain user successfully logs in a cookie ( httpOnly ) with jwt token as value is being stored inside of a browser. Now after user logs in I dispatch an login action after which I redirect user to Home Page, so inside Login Page I have this :
const handleFormSubmit = (e)=>{
e.preventDefault();
dispatch(login_action(loginFormData));
history.push("/");
}
};
Now inside of a Home Page I dispatch an action called get_cookie_action which will make an Api call to a NodeJs backend ( where I check if jwt inside of a cookie is valid ) and return true or false depending of cookie state. This is get_cookie_action :
export const get_cookie_action = () => async (dispatch) =>{
try {
dispatch({type:'GET_COOKIE_REQUEST'});
const { data } = await api.get_cookie();
dispatch({
type : 'GET_COOKIE_LOGGED_IN',
payload : data
});
} catch (error) {
dispatch({
type : 'GET_COOKIE_LOGGED_OUT',
payload : error.response.data
});
}
};
This is get_cookie_reducer :
export const get_cookie_reducer = ( cookie = {} , action ) =>{
switch(action.type) {
case 'GET_COOKIE_REQUEST' :
return {
loading : true
}
case 'GET_COOKIE_LOGGED_IN' :
return {
loading : false,
cookie : action.payload
}
case 'GET_COOKIE_LOGGED_OUT' :
return {
loading : false,
cookie : action.payload
}
default :
return cookie;
};
In Home Page I dispatch an action for getting a cookie value through get_cookie_action and check for that cookie, so I have this inside of a Home Page :
React.useEffect(()=>{
dispatch(get_cookie_action());
},[]);
and above I have:
const cookie_info = useSelector( state => state.is_user_logged_in );
const { cookie, loading } = cookie_info;
And I return this :
return (
<>
{
typeof cookie !== 'undefined'
?
(
loading
?
<h1>loading...loading...loading...</h1>
:
(
cookie
?
<h1> You are logged in ! </h1>
:
<Redirect to="login"/>
)
)
:
null
}
</>
);
The main problem is that after user logs in he cannot access Home Page because
<Redirect to="login"/>
is being fired immediately and React is not waiting for a cookie state to change from {} which is initial state of a cookie in reducers to true.