AsyncStorage in React Native

Posted on 2020-03-24 by Burak Hamdi TUFAN
Mobile
AsyncStorage in React Native
Hello everyone, in this article we are going to talk abiut AsyncStorage. We will learn what it is and make an example about asyncstorage and store and use data from Device Local Storage.

Let's get started.

Firstly take a little look at What AsyncStorage is:

AsyncStorage is an unencrypted, asynchronous and persistent, key-value storage system to keep datas for using globally at your project. It works with key-value pairs. It is based on JavaScript.

On iOS, AsyncStorage is backed by native code that stores small values in a serialized dictionary and larger values in separate files. On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.

Async Storage works as asynchronous and it returns promise objects when there is no error and return error objects when error occured.

All values are persistent on AsyncStorage so the data has been writes on the storage and recorded data will be there until recorded data has been removed. And when you run the application again you can use these recorded datas.

First Let's install Async Storage in our project.

$ yarn add @react-native-community/async-storage

and link it our project:

Over React Native 0.60 it will be auto linked under 0.59 we will use below code block.


$ react-native link @react-native-community/async-storage

Now lets make a simple a SignUp/Login example with AsyncStorage:

We will use the below methods to record and remove data at AsyncStorage:

  • setItem($key, $value) : For recording data with specified key.
  • getItem($key) : To fetch data from recorded datas
  • removeItem($key) : For removing data with specified $key value.

To record data below code block will be run


storeData = async () => {
  try {
    await AsyncStorage.setItem('@storage_Key', 'stored value')
  } catch (e) {
    // saving error
  }
}
To read data

getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

First import react-native async-storage in our project.


import AsyncStorage from '@react-native-community/async-storage';
Below code block will create Sign Up page and the method.

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Dimensions,
  Alert,
  TextInput,
} from 'react-native';

import AsyncStorage from '@react-native-community/async-storage';

export default class SignUpPage extends Component<{}> {
  constructor(props) {
    super(props);
    this.state = {
      signUpEmail: '',
      signUpPassword: '',

    };
  }

  fncSystemSignUp = async () => {
	if(this.state.signUpEmail != "" && this.state.signUpPassword != "" )
	{
		try {
		    await AsyncStorage.setItem('email', this.state.signUpEmail);
		    await AsyncStorage.setItem('@password', this.state.signUpPassword);
		  } catch (e) {
		    
		  }
  	}
}
  render() {
      return(
          

            "SignUp"

            

            
               this.setState({signUpEmail: value})}
                placeholder="Email (*)"/>
            
            
            
               this.setState({signUpPassword: value})}
                value={this.state.signUpPassword}
                placeholder="Password (*)"/>
            
            
            
              

Now from above code block you can see the below code will record the values. Below code block will check the required values if entered make recording.


  fncSystemSignUp = async () => {
	if(this.state.signUpEmail != "" && this.state.signUpPassword != "" )
	{
		try {
		    await AsyncStorage.setItem('email', this.state.signUpEmail);
		    await AsyncStorage.setItem('password', this.state.signUpPassword);
		  } catch (e) {
		    
		  }
  	}
}

Now let's get data and check equality login values.

Below code block will build a simple login page.

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  Button
} from 'react-native';

export default class LoginPage extends Component<{}> {
    constructor(props) {
    super(props);
    this.state = {
      userEmailOrUsername: "",
      userPassword: "",
    };
  }

  fncSystemLogin = async () => {
    if(this.state.userEmailOrUsername != "" && this.state.userPassword != "" )
    {
      try {
          const email = await AsyncStorage.getItem('email');
          const password = await AsyncStorage.getItem('password');
          if(email !== null && password !== null) {
            if(email === this.state.userEmailOrUsername && 
              password === this.state.userPassword)
            {
              //Login successfull
            }
            else{
              //Login inputs are incorrect
            }
          }
        } catch (e) {
          
        }
    }
}

  render() {
    return(
      

        Login            
            
              
                 this.setState({userEmailOrUsername: value})}
                  placeholder="Username or Email"/>
              
              
                 this.setState({userPassword: value})}
                  value={this.state.userPassword}
                  placeholder="Password"/>
              
              
                

At the above code block you can see the below code block will make the getting and checking the equality the recorded datas and inputted datas.


  fncSystemLogin = async () => {
    if(this.state.userEmailOrUsername != "" && this.state.userPassword != "" )
    {
      try {
          const email = await AsyncStorage.getItem('email');
          const password = await AsyncStorage.getItem('password');
          if(email !== null && password !== null) {
            if(email === this.state.userEmailOrUsername && 
              password === this.state.userPassword)
            {
              //Login successfull
            }
            else{
              //Login inputs are incorrect
            }
          }
        } catch (e) {
          
        }
    }
}

Now we are eady to use Async Storage in our projects.

That is all in this article.

Have a good Async Storaging

Burak Hamdi TUFAN


Tags
Share this Post
Send with Whatsapp