This mistake is caused by returning something in the useEffect function.
Can only return nothing or a clean-up function in useEffect function:
Wrong usage:
useEffect(()=>getData(),[])
async function getData() {
const url = "http://localhost:8080/hello";
try {
const response = await fetch(url);
setData(response)
} catch (error) {}
}
getData returns a promise because it is declared to be async. This promise will eventually be resolved when asynchronous operations (like fetch) complete.
Cannot return a promise in useEffect function. Only return nothing or the clean-up function.
Correct usage: write asynchronous functions in useEffect and call them so that the useEffect function returns nothing.
useEffect(() => {
async function getData() {
const url = "http://localhost:8080/hello";
try {
const response = await fetch(url);
setData(response);
} catch (error) {}
}
getData();
}, []);
Top comments (0)