Since the React useEffect callback function cannot be async, you can do either of the following:
#Create a Self-Invoking Anonymous Function
You can simply create a self-invoking anonymous function inside the useEffect hook that does the asynchronous call(s) and performs other related tasks. For example:
// ...
useEffect(() => {
(async function() {
const products = await fetch(`${API_URL}/products.json`);
setProducts(products);
})();
}, []);
// ...
#Create a Nested Named Function
You can create a named asynchronous function that you can call right after it is declared, for example, like so:
// ...
useEffect(() => {
const fetchData = async () => {
const products = await fetch(`${API_URL}/products.json`);
setProducts(products);
});
fetchData();
}, []);
// ...