Can someone tell me why this error occurs?

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.

hello and welcome back to fcc forum :slight_smile:

how exactly are these two scenarios are different?!

1 Like

What line? What error? What does “this” mean?

You have a syntax error in the first code. You closed the function and have an unclosed if statement

1 Like

In the firts case the token is save in localStorage. and all run okay.
In the second case the token is delete from localStorage.
context: when i run the second code for any rason usuarioAutenticado(); run one time before any component and not finding a token because one has not yet been generated, it jumps to the catch and deletes the token that is generated after a few seconds. i use react strict mode.

the component

the code of usuarioAutenticado()

the result of the console and localStorage:

the code of usuarioAutenticado()


the result of the console and localStorage:

Continuing the discussion from Can someone tell me why this error occurs?:
more information:
React stay in react strict mode.
the component that is rendered after registering user:
The components before proyectos save the token that is the result of an api call (localapi).


usuarioAutenticado(); code

the console result

for some reason usuarioAutenticado(); code is called before the component recibed the token and this send error and Token is deleted. Why is this happening?

but when i put the code like this:


all works but usuarioAutenticado(); code is called like null one firts moment.

I have merged the two threads as they are about the same question.

why dont you make sure that component gets run only when it’s “ready”, to begin with?

1 Like

i verifequed the token is ready and the null response of console its over, and all works.
the solution is this.
image

and is important call the token in app.js component

good job and happy coding javicoro99 :smiley: