Reputation: 5150
Why can't useEffect()
use async-await?
const Home: React.FC = () => {
useEffect(async () => {
console.log(await ecc.randomKey())
}, [])
return (
...
The error I get is
Argument of type '() => Promise' is not assignable to parameter of type 'EffectCallback'.
Type 'Promise' is not assignable to type 'void | (() => void | undefined)'.
Type 'Promise' is not assignable to type '() => void | undefined'.
Type 'Promise' provides no match for the signature '(): void | undefined'.ts(2345)
Upvotes: 74
Views: 76798
Reputation: 746
I read the answers and all the answers are correct but the "native ones" (the ones not using a third-party package) don't allow you to do two things:
I found this method which enables both
const Component= ()=>{
const effectHandler = async()=>{
// Do some async stuff
}
useEffect(()=>{
effectHandler()
}, [])
// reuse effectHandler
effectHandler()
return(<></>)
}
Upvotes: 0
Reputation: 9504
You can use an IIFE (asynchronous anonymous function which executes itself) like so:
useEffect(() => {
// Some synchronous code.
(async () => {
await doSomethingAsync();
})();
return () => {
// Component unmount code.
};
}, []);
Upvotes: 41
Reputation: 9504
You can use the use-async-effect
package which provides a useAsyncEffect
hook:
useAsyncEffect(async () => {
await doSomethingAsync();
});
Upvotes: 1
Reputation: 2651
Declaring the effect as async function is not recommended. But you can call async functions within the effect like following:
useEffect(() => {
const genRandomKey = async () => {
console.log(await ecc.randomKey())
};
genRandomKey();
}, []);
More here: React Hooks Fetch Data
Upvotes: 89