Is it already possible to use top-level await in react-native? I saw it's been added to TypeScript 3.8 (I was not using TS, I just tried to see if it would help but no). However in react-native file transform is handled by babel and I don't think the current metro preset handles top-level awaits. Is there any way to make it work?
Top level await You can use the await keyword on its own (outside of an async function) within a JavaScript module. This means modules, with child modules that use await , wait for the child module to execute before they themselves run. All while not blocking other child modules from loading.
The ECMAScript feature 'Top-level await' which is promoted to Stage 4 in the TC39 process lets us use the asynchronous await operator at the top level of modules. Top-level await enables modules to act as big async functions. With top-level await, ECMAScript Modules (ESM) can await resources.
js modules.
To solve the error "Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext'", use the await keyword in an async function or set the module option to es2022 and target to es2017 in your tsconfig. json file.
Using await will make sure the promises returned by both methods will be done before the next line is run. We call getAndSetData in the useEffect callback that’s called with an empty array to run it when the component mounts. To use await keyword on React Native, we can use it in an async function.
Plus you can use try/catch for proper error handling. async/await is convenient and clean: at some point you may want to introduce it in your React components too. Let's see how. Before starting off make sure to have a React development environment.
Let's say you want to fetch data from an API. It's standard React stuff, you put the API call in componentDidMount and that's it: (This component is a contrived example: there's no error handling. Let’s assume we're in the happy path and nothing goes wrong with our fetch call).
Used mostly for data fetching and other initialization stuff componentDidMount is a nice place for async/await. Here are the steps to follow: Now, create-react-app supports async/await out of the box. But if you have a webpack boilerplate you may hit an error (more in a minute).
ECMAScript feature top-level await stands on two conditions:
But React-Native uses node modules, so the answer is no.
See Ecma international standard for more
EDIT:
According to comment and more is possible in Node.js. But React-Native uses V8, which supports it too. It just compiles JSX to C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With