Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native AsyncStorage fetches data after rendering

Tags:

react-native

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.

like image 337
skleest Avatar asked Nov 05 '15 19:11

skleest


People also ask

Where does AsyncStorage save data React Native?

On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.

Does AsyncStorage persist?

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.

What does AsyncStorage getItem return?

getItem() returns a single value AND a promise.


1 Answers

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.

like image 53
jasonmerino Avatar answered Sep 26 '22 04:09

jasonmerino