Persist Data Using AsyncStorage in React Native

Author - Dalbir Kaur
11.10.2019
|
0 Comments
||

Persist Data Using AsyncStorage in React Native

There are various ways to preserve the data in React Native but AsyncStorage is the most recommended way to persist data in your React Native applications as it is a built-in feature.

AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system that is global to the app. Data is stored as strings and must be serialized before it can be saved and de-serialized before retrieval.

Suppose you have a form that has a name, email and message fields. You want to store data whenever the user does any change. When the user will come back to the same page, if the user left something unsaved last time, then you will show a popup asking the user if he wants to populate the unsaved data or to discard that data.

Below are the steps to accomplish this in the React Native app.

This is the code that stores form data in the React Native app.

Step 1: Import the “AsyncStorage” into our file where you want to use it.

import { AsyncStorage } from 'react-native';

Step 2: Create the below text inputs in your component render function.

<TextInput 
placeholder="Name"
onChangeText={(text) => this.handleChange(‘name’,text)}
/>
<TextInput 
	placeholder="Email"
keyboardType="email-address”
onChangeText={(text) => this.handleChange(‘email’,text)}
/>
<TextInput 
	placeholder="Address"
onChangeText={(text) => this.handleChange(‘address’,text)}
/>

– Create a common function “handleChange” that is called when any of TextInput value is changed and it set the value in state and also stores it in AsyncStorage.

handleChange = (key, value) => 
                      {
        		console.log(key+' '+value);
       		 this.setState({[key]: value},
           		 function() 
                         {
                		AsyncStorage.setItem(key, value);
           		 }
        		);
    	             }

Step 3: To show the popup, when the user will come back to that page if he/she let something unsaved. You can provide two buttons to the user “Populate Data” and “Discard Data”. If user clicks on populate then a function will fetch all the values and set them in state and if user clicks on the discard button then delete all the stored values.

Add the below code to your componentDidMount function.

		componentDidMount()
                                      {
			let data = AsyncStorage.getAllKeys().then(async(keys) => 
                                         {
            return keys.filter(function(item) 
                                             {
		let fields = [‘name’,’email’,’address’];
                	if(fields.includes(item))
                                                  {
                   		return true;
                	                          }
                	return false;
                                             });
        	                        });
	if(data)
                   {
		Alert.alert(
 	'Populate Unsaved Data',
  	'It seems that you have some unsaved data.',
  [
    	              {
      text: 'Populate',
      onPress: () => this.setState(data)
                      },
    {text: ‘Discard’, onPress: () =>this.discard},
  ],
  {cancelable: false},
);
                   }
                             }
discard = () =>
{
	let keys = [‘name’,’email’,’address’];
AsyncStorage.multiRemove(keys); 
}

Note:
If you want to store boolean values in it then you should stringify the value first.
Like:

JSON.stringify(value)
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *