Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
React useEffect is not triggering on redirect

i have a function called login that redirects the user to the main page if everything was ok. Then, on the main page, i want to fetch some user info with useEffect using the token the was stored when the user logged in, but nothing happens. Only when i refresh the page i get the data.

login function

export const login = ({ email, password, history }) => {
  return async (dispatch) => {
    try {
      const response = await fetch("http://localhost:5000/api/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email,
          password,
        }),
      });

      const data = await response.json();

      if (data.status === 200) {
        localStorage.setItem("userToken", data.user);
        history.push("/");
      } else {
        dispatch(
          setNotification({
            variant: "error",
            message: data.message,
          })
        );
      }
    } catch (e) {
      console.log(e.message);
    }
  };
};

fetch user funtion

export const fetchUser = () => {
  return async (dispatch) => {
    try {
      const response = await fetch("http://localhost:5000/userInfo", {
        headers: {
          "x-access-token": localStorage.getItem("userToken"),
        },
      });

      const data = await response.json();
      dispatch(setUser({
        id: data.id,
        fullname: data.fullname,
        email: data.email
      }))
    } catch (error) {}
  };
};

useEffect on my main page

useEffect(() => {
     dispatch(fetchUser()); 
  }, []);

backend function

module.exports.getCurrentUser = async (req, res) => {
  const token = req.headers["x-access-token"];
  try {
    const verifyToken = jwt.verify(token, "123");
    const user = await User.findOne({ email: verifyToken.email });
    return res.json({
      id: user._id,
      fullname: user.fullname,
      email: user.email
    })
  
  } catch (error) {}
};
about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

The 2nd parameter to useEffect tells it when it needs to run. It only runs if one of the values in the array has changed. Since you pass an empty array, none of the values in it have changed.

This is presuming your app probably starts at '/', then detects there is no user so switches to the login screen. When it goes back to the root, it only executes useEffect if something in the array has changed from the previous render.

As it is, the isMounted doesn't make much sense. This could simply be:

useEffect(() => {
      dispatch(fetchUser());
  });
about 4 years ago · Santiago Gelvez Denunciar

0

You're calling setUser, but what is calling your login function?

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda