You can't use an await
in a useEffect by default, but on top of that, you shouldn't make your useEffect callback async at all. Instead, make an async function within the effect.
React.useEffect(() => {
// Create an async function...
async function runEffect() {
const url = `${API}/get-profile?id=${userId}`;
const res = await fetch(url);
const json = await res.json();
setUser(json);
}
// ...and then invoke it:
runEffect();
}, [userId]);
Note that if you want to update state from a async function, do it within the async function.
This is because useEffect
is not allowed to return a promise.
An async function also lets us return a cleanup function. [[20220704105955-useeffect-cleanup-function]]
https://devtrium.com/posts/async-functions-useeffect https://www.joshwcomeau.com/react/common-beginner-mistakes/#async-effect-function-9