Nir Benita
Nir Benita

Reputation: 511

Unexpected behavior when fetching data with hooks

I'm trying to fetch data with hooks, and I'm getting an unexpected result.

When I try to use an async callback with useEffect, it throws a warning saying it's bad practice, even though the code works (Commented out in the attached example below)

But when I try to declare an async function within useEffect, it doesn't work (example below)

What am I missing? https://codesandbox.io/s/mystifying-aryabhata-glqwz?fontsize=14

Upvotes: 4

Views: 72

Answers (4)

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2786

look to this solution in the simple solution

Upvotes: 1

AngelSalazar
AngelSalazar

Reputation: 3113

the callback passed to useEffect must return either a cleanup callback or undefined, when you mark a function as async, it returns a promise implicitly

you can create a function inside the useEffect callback that you can mark as async

React.useEffect(() => {
 async function fetchData() {
  // write your request
 }
 fetchData();
})

Upvotes: 1

Anton Bahurinsky
Anton Bahurinsky

Reputation: 456

You should put all the effect logic inside the fetchData() and the call it separately within the useEffect:

useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await axios("https://hn.algolia.com/api/v1/search?query=redux");
        setData(result.data);
      } catch (e) {
        console.log(e);
      }
    }
    fetchData();
  }, []);

Upvotes: 3

Mohamed Ramrami
Mohamed Ramrami

Reputation: 12691

You can fix it like this :

  useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await axios(
          'https://hn.algolia.com/api/v1/search?query=redux',
        );

        setData(result.data);
      } catch(e) {
        console.log(e);
      }
    }

    fetchData();
  }, []);

https://codesandbox.io/s/cocky-water-c0w9i

The problem in your code was, in these lines :

  const result = fetchData();
  setData(result.data);

here fetchData is async and will return a promise not the actual result, and so result.data is undefined

Upvotes: 2

Related Questions