Reputation: 511
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
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
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
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