Home > Mobile >  Async function inside useEffect return undefined
Async function inside useEffect return undefined

Time:12-05

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)

CodePudding user response:

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

CodePudding user response:

It looks like you're trying to use the fetchData function inside the useEffect hook, but you're not returning it. The useEffect hook expects the function you pass to it to return a cleanup function, or nothing at all.

You can fix this by either returning the fetchData function from the useEffect hook, or by making the fetchData function itself a callback that gets passed to useEffect directly. Here's an example of how you could do that:

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

    // Call the fetchData function directly
    fetchData();
}, []);

Alternatively, you could return the fetchData function from the useEffect hook like this:

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

}

// Return the fetchData function so it can be used as a cleanup function return fetchData; }, []);

Either of these approaches should allow you to see the output from the checkLogin function in the console.

  • Related