Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!