Search code examples
reactjsreact-hooksasync-awaitnext.jstry-catch

Async function inside useEffect return undefined


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

  • 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;
    }