Don't async await, especially in useEffect
Often I need to setState
based on an async value. With hooks this is something like:
useEffect(async () => {
const newVal = await asyncCall();
setVal(newVal);
});
But wait!. This throws an error. React wants the return of useEffect
to be a cleanup function.
The return type of an async
function is Promise
. So that won't work. Best to just put on your big developer pants and use that promise.
useEffect(() => {
asyncCall().then(setVal);
})
There. Now our useEffect
returns undefined
, and React is pleased.
Here is a sandbox if you want to see for yourself.
Tweet