I try to get the user information from the API and check that if it is isAuthenticated === true go to the profile page, otherwise to the login page,But since JavaScript does not wait for a response, it executes the code one after the other and checks the condition with the same initialization as false.
What should I do to wait for a response from the API and change the value of isAuthenticated and userInfo and then check the following condition?
const userLoad = useSelector(state => state.userLoad)
const {error, loading, isAuthenticated, userInfo} = userLoad
useEffect(() => {
if (isAuthenticated) {
dispatch(getUserDetails('profile'))
} else {
history.push('/login')
}
}, [dispatch, history, isAuthenticated, userInfo])
I created a userLoadReducer which is as follows:
export const userLoadReducer = (state = {}, action) => {
const {type, payload} = action;
switch (type) {
case USER_LOADED_REQUEST:
return {
...state,
loading: true
}
case USER_LOADED_SUCCESS:
return {
...state,
loading: false,
isAuthenticated: true,
userInfo: payload.user,
}
case USER_LOADED_FAIL:
return {
...state,
loading: false,
isAuthenticated: false,
userInfo: null
}
default:
return state
}
}
And its load_user action is as follows:
export const load_user = () => async dispatch => {
const config = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
};
try {
dispatch({type: USER_LOADED_REQUEST});
const response = await axios.get(`/auth/user/`, config);
if (response.status === 200) {
dispatch({
type: USER_LOADED_SUCCESS,
payload: response.data
});
} else {
dispatch({
type: USER_LOADED_FAIL
});
}
} catch (err) {
dispatch({
type: USER_LOADED_FAIL
});
}
};
inspect: console.log()
| Order | Result
| -------- | ---------------------------------------------------- |
| First | {loading: false, isAuthenticated: false, userInfo: null} |
| Second | {loading: true, isAuthenticated: false, userInfo: null} |
| third | {loading: false, isAuthenticated: true, userInfo: {…}} |