I am using AsyncStorage
in ComponentWillMount
to get locally stored accessToken
, but it is returning the promise after render()
function has run. How can I make render()
wait until promise is completed? Thank you.
On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.
AsyncStorage is a simple, asynchronous, unencrypted by default module that allows you to persist data offline in React Native apps. The persistence of data is done in a key-value storage system.
getItem() returns a single value AND a promise.
You can't make a component wait to render, as far as I know. What I've done in the app I'm working on is to add a loading screen until that promise from AsyncStorage resolves. See the examples below:
// // With class component syntax // import React from 'react'; import { AsyncStorage, View, Text } from 'react-native'; class Screen extends React.Component { state = { isLoading: true }; componentDidMount() { AsyncStorage.getItem('accessToken').then((token) => { this.setState({ isLoading: false }); }); }, render() { if (this.state.isLoading) { return <View><Text>Loading...</Text></View>; } // this is the content you want to show after the promise has resolved return <View/>; } }
// // With function component syntax and hooks (preferred) // import React, { useEffect } from 'react'; import { AsyncStorage, View, Text } from 'react-native'; const Screen () => { const [isLoading, setIsLoading] = useState(true); useEffect(() => { AsyncStorage.getItem('accessToken').then((token) => { setIsLoading(false); }); }, []) if (isLoading) { return <View><Text>Loading...</Text></View>; } // this is the content you want to show after the promise has resolved return <View/>; }
Setting the isLoading
property in state will cause a re-render and then you can show the content that relies on the accessToken.
On a side note, I've written a little library called react-native-simple-store that simplifies managing data in AsyncStorage. Hope you find it useful.
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