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
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();
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With