Im building a full stack aplication and this error occurs:
(i use React, express, useReducer, useContext)
import React, { useReducer } from "react";
import {
CERRAR_SESION,
LOGIN_ERROR,
LOGIN_EXITOSO,
OBTENER_USUARIO,
REGISTRO_ERROR,
REGISTRO_EXITOSO,
} from "../../types";
import authReducer from "./authReducer";
import authContext from "./authContext";
import clienteAxios from "../../config/axios.js";
import tokenAuth from "../../config/tokenAuth";
const AuthState = (props) => {
const initialState = {
token: localStorage.getItem("token"),
autenticado: null,
usuario: null,
mensaje: null,
};
const [state, dispatch] = useReducer(authReducer, initialState);
// FUNCIONES
const registrarUsuario = async (datos) => {
try {
const respuesta = await clienteAxios.post("/api/usuarios", datos);
console.log(respuesta.data);
// FUNCIONA
dispatch({
type: REGISTRO_EXITOSO,
payload: respuesta.data,
});
// Obtener usuario
// De aqui en adelante error BORRA el local storage
usuarioAutenticado();
// Arriba en la funcion lo errores si se atrapan
} catch (e) {
//FUNCIONA BIEN
console.log(e);
const alerta = {
msg: e.response.data.msg,
categoria: "alerta-error",
};
dispatch({
type: REGISTRO_ERROR,
payload: alerta,
});
}
};
// Retorna el usuario autenticado
const usuarioAutenticado = async () => {
const token = localStorage.getItem("token");
console.log(token);
if (token) {
// Esto funciona
// FUNCIÓN PAR ENVIAR EL TOKEN POR HEADERS
tokenAuth(token);
try {
const respuesta = await clienteAxios.get("/api/auth");
console.log(respuesta);
dispatch({
type: OBTENER_USUARIO,
payload: respuesta.data.usuario,
});
} catch (e) {
console.log("Pase por aqui");
console.log(e.response);
dispatch({
type: LOGIN_ERROR,
});
}
}
};
// Cuando el usuario inicia sesion
const iniciarSesion = async (datos) => {
try {
const respuesta = await clienteAxios.post("/api/auth", datos);
dispatch({
type: LOGIN_EXITOSO,
payload: respuesta.data,
});
// Obtener el usuario
usuarioAutenticado();
} catch (e) {
// console.log(e);
const alerta = {
msg: e.response.data.msg,
categoria: "alerta-error",
};
dispatch({
type: LOGIN_ERROR,
payload: alerta,
});
}
};
// Cierra la sesion del usuario
const cerrarSesion = () => {
dispatch({
type: CERRAR_SESION,
});
};
return (
<authContext.Provider
value={{
token: state.token,
autenticado: state.autenticado,
usuario: state.usuario,
mensaje: state.mensaje,
registrarUsuario,
iniciarSesion,
usuarioAutenticado,
cerrarSesion,
}}
>
{props.children}
</authContext.Provider>
);
};
export default AuthState;
reducer code:
import {
CERRAR_SESION,
LOGIN_ERROR,
LOGIN_EXITOSO,
OBTENER_USUARIO,
REGISTRO_ERROR,
REGISTRO_EXITOSO,
} from "../../types";
export default (function (state, action) {
switch (action.type) {
case REGISTRO_EXITOSO:
case LOGIN_EXITOSO:
localStorage.setItem("token", action.payload.token);
return {
...state,
autenticado: true,
mensaje: null,
};
case OBTENER_USUARIO:
return {
...state,
autenticado: true,
usuario: action.payload,
};
case CERRAR_SESION:
case LOGIN_ERROR:
case REGISTRO_ERROR:
localStorage.removeItem("token");
return {
...state,
token: null,
usuario: null,
autenticado: null,
mensaje: action.payload,
};
default:
return state;
}
});
my error is when i put this line :
const usuarioAutenticado = async () => {
const token = localStorage.getItem("token");
console.log(token);
if (token) {
// Esto funciona
// FUNCIÓN PAR ENVIAR EL TOKEN POR HEADERS
tokenAuth(token);
};
try {
const respuesta = await clienteAxios.get("/api/auth");
console.log(respuesta);
dispatch({
type: OBTENER_USUARIO,
payload: respuesta.data.usuario,
});
} catch (e) {
console.log("Pase por aqui");
console.log(e.response);
dispatch({
type: LOGIN_ERROR,
});
}
}
when put the try catch outside, the localstorage is empty
but when i put like this:
const usuarioAutenticado = async () => {
const token = localStorage.getItem("token");
console.log(token);
if (token) {
// Esto funciona
// FUNCIÓN PAR ENVIAR EL TOKEN POR HEADERS
tokenAuth(token);
try {
const respuesta = await clienteAxios.get("/api/auth");
console.log(respuesta);
dispatch({
type: OBTENER_USUARIO,
payload: respuesta.data.usuario,
});
} catch (e) {
console.log("Pase por aqui");
console.log(e.response);
dispatch({
type: LOGIN_ERROR,
});
}
}
};
all works.