Sometimes, we want to use await keyword on React Native.
In this article, we’ll look at how to use await keyword on React Native.
How to use await keyword on React Native?
To use await keyword on React Native, we can use it in an async
function.
For instance, we write:
import * as React from 'react';
import { View, AsyncStorage } from 'react-native';
import Constants from 'expo-constants';
import AssetExample from './components/AssetExample';
import { Card } from 'react-native-paper';
export default function App() {
const getAndSetData = async () => {
const key = 'data';
await AsyncStorage.setItem(key, 'value');
const value = await AsyncStorage.getItem(key);
console.log(value);
};
React.useEffect(() => {
getAndSetData();
}, []);
return <View></View>;
}
to use await
when calling AsyncStorage.getItem
and AsyncStorage.setItem
.
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.
Conclusion
To use await keyword on React Native, we can use it in an async
function.