Intento obtener la información del usuario de la API y verifico que si es Autenticado === verdadero vaya a la página de perfil, de lo contrario a la página de inicio de sesión, pero como JavaScript no espera una respuesta, ejecuta el código uno después del other y verifica la condición con la misma inicialización como false.
¿Qué debo hacer para esperar una respuesta de la API y cambiar el valor de isAuthenticated y userInfo y luego verificar la siguiente condición?
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])Creé un userLoadReducer que es el siguiente:
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 } }Y su acción load_user es la siguiente:
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 }); } };inspeccionar: consola.log()
| Order | Result | -------- | ---------------------------------------------------- | | First | {loading: false, isAuthenticated: false, userInfo: null} | | Second | {loading: true, isAuthenticated: false, userInfo: null} | | third | {loading: false, isAuthenticated: true, userInfo: {…}} |