Async function inside useEffect return undefined

Async function inside useEffect return undefined

Problem Description:

I have an async function inside useEffect

  useEffect(() => {
    async function fetchData() {
      const res = await checkLogin();
      console.log(res);
    }

    fetchData();
  }, []);

checkLogin returning "Hello world"

 async function checkLogin() {
  try {
  const resp = await linstance.get("/api/auth/user");

  setUser(resp.data.user);
  setEmail(resp.data.email);
  setId(resp.data.id);

  return "Hello world";
} catch (error) {
  return error.response;
}

}

why in the console.log it’s print undefined?

I want checkLogin response to be "Hello world" (to make it clear)

Solution – 1

Inside checkLogin() your code has try/catch. If try block run successfully, you would get "Hello world" in the console.

But most likely your code is falling into the catch block. it is throwing error and error object has no response property. In the catch block

 catch (error) {
  // check what is logging here
  console.log("error in fetchLogin", error)
  return error.response;
}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject