简体   繁体   中英

how yo use an async method inside useEffect() hook

I need to fetch an api in an useEffect() . I tried to do it and it throws me the following error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

My code is the following:

-Api I need to fetch:

export const fetchMyApi = async (code) => {
  const { data } = await useQuery("data", () =>
    clientAPIs.getData(code)
  );
  return data;
};

-My useEffect code:

  useEffect(() => {
    await fetchMyApi(values.code)
  }, [values]);

I have found many issues about this on internet but they all offer basically the same solution such as:

  useEffect(() => {
    fetchMyApi(values.code)
      .then((data) => {
        return data?.options;
      })
      .then((data) => {
        console.log(data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, [values]);

or

  useEffect(() => {
    let didCancel = false;
    async function fetch() {
      const result = await fetchMyApi(values.code);
      if (!didCancel) {
        console.log(result);
      }
    }
    fetch();
    return () => {
      didCancel = true;
    }; 
  }, [values]);

None of those works in my case. I am using Nextjs framework.

What should I try?

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

You are breaking the rules of hooks. Hooks are only valid when called while synchronously rendering a React component. An effect runs separately after a componenent renders. So you cannot call a hook from an effect.

And yes you are calling a hook from an effect because this effect:

  useEffect(() => {
    await fetchMyApi(values.code)
  }, [values]);

Calls the fetchMyApi function, which calls a hook:

await useQuery('data', () => /* ... */)

You are using react query incorrectly.

First make your fetchMyApi just do it's async task, and nothing else:

export const fetchMyApi = (code) => {
  return clientAPIs.getData(code)
};

Then call useQuery from the root of your functional component:

function MyComponent() {
  const { data } = useQuery('data', () => fetchMyApi('some code here'))
}

The documentation should take you the rest of the way from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM