AsyncStorage in React Native

AsyncStorage in React Native

Hello everyone, in this article we are going to talk abiut AsyncStorage. We will leran what it is and tgen make an example about asyncstorage.

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( <View style={{backgroundColor: '#f8f8ff', borderRadius:2, borderWidth: 1}}> <Text style={styles.modalTitleStyle} >"SignUp"</Text> <View style={{ borderBottomColor: 'black', borderBottomWidth: 1, }} /> <View> <TextInput style={{height: 50}} value={this.state.signUpEmail} onChangeText={(value) => this.setState({signUpEmail: value})} placeholder="Email (*)"/> </View> <View> <TextInput style={{height: 50}} onChangeText={(value) => this.setState({signUpPassword: value})} value={this.state.signUpPassword} placeholder="Password (*)"/> </View> <View style={{height: 50}}> <Button title="Sign Up" color="#4285f4" onPress={this.fncSystemSignUp.bind(this)} /> </View> </View> ); } } const styles = StyleSheet.create({ modalTitleStyle:{ fontSize: 20, fontWeight: 'bold', } });

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( <View style={{marginTop: 22,marginLeft: 22,marginRight:22 }}> <Text style={styles.modalTitleStyle}>Login</Text> <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', padding: 15 }}> <View> <TextInput style={{height: 50}} value={this.state.userEmailOrUsername} onChangeText={(value) => this.setState({userEmailOrUsername: value})} placeholder="Username or Email"/> </View> <View> <TextInput style={{height: 50}} onChangeText={(value) => this.setState({userPassword: value})} value={this.state.userPassword} placeholder="Password"/> </View> <View style={{ height: 50 }}> <Button title="Login" color="#4285f4" onPress={this.fncSystemLogin.bind(this)} /> </View> </View> ); } } const styles = StyleSheet.create({ modalTitleStyle:{ fontSize: 20, fontWeight: 'bold', } });

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


Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment.

Comments

    There is no comment. Be the owner of first comment...