React’s useEffect() expects the first argument to be a callback that returns either undefined or another function. But since an async function returns a Promise, it’s not a valid argument for the useEffect() hook otherwise an exception will be thrown:
// this does not work!!!
useEffect(async () => {
try {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
);
const post = await response.json();
console.log(post);
} catch (e) {
console.error(e);
}
}, []);
A workaround is to define the async function inside the callback and then call it:
useEffect(() => {
function fetchPost() {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
);
const post = await response.json();
// do something with the data
console.log(post);
}
fetchPost();
}, []);
Or you can use an IIFE (Immediately-Invoked Function Expressions):
useEffect(() => {
// the IIFE
(async function fetchPost() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const post = await response.json();
// do something with the data
console.log(post);
})();
}, []);