React TypeScript 16.8 How to make useEffect() async
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
You can use an asynchronous anonymous function which executes itself like so:
useEffect(() => { // Some synchronous code. (async () => { await doSomethingAsync(); })(); return () => { // Component unmount code. };}, []);
Why
Using an async function in useEffect
makes the callback function return a Promise instead of a cleanup function.
Solution
useEffect(() => { const foo = async () => { await performPromise() }; foo();}, []);
OR with IIFE
useEffect(() => { (async () => { await performPromise() })()}, []);