TS1308

error TS1308: ‘await’ expressions are only allowed within async functions and at the top levels of modules.ts.

Broken Code ❌

1
2
3
4
5
React.useEffect(() => {
const myPromise = Promise.resolve;
await myPromise();
console.log('Promise is resolved.');
}, []);

Fixed Code ✔️

You cannot use an await expression in an useEffect hook, but you can use legacy Promise calls:

1
2
3
4
5
6
React.useEffect(() => {
const myPromise = Promise.resolve;
myPromise().then(() => {
console.log('Promise is resolved.');
});
}, []);

Alternatively, you can use an IIFE (Immediately-invoked Function Expression) in your useEffect hook:

1
2
3
4
5
React.useEffect(() => {
(async () => {
await Promise.resolve();
})();
}, []);