Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 221
Nir Benita Avatar asked Mar 04 '23 13:03

Nir Benita


1 Answers

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();
  }, []);
like image 99
Anton Bahurinsky Avatar answered Mar 17 '23 07:03

Anton Bahurinsky