AsyncStorage in React Native

Hey Guys!! Good Day!!

AsyncStorage Component is a simple storage system, that is globally available to React Native Application. It is persistent, means data that has been stored will continue to exist even when quiting or restarting Application or your phone. Its also asynchronous, as its name implies. 

The following are some of the main methods for AsyncStorage
  • setItem
  • getItem
  • removeItem
  • clear
  • multiSet
  • multiGet
  • multiRemove
Optionally, we can add a callback to the methods. To know more methods in AsyncStorage, refer AsyncStorage.


setItem
This method is to save key and its value in AsyncStorage.

                  AsyncStorage.setItem('key', 'value')
                                        .then( () =>{
                                                //Operation to do
                                       });
getItem
This method is to get the saved value, using its key.

                   AsynStorage.getItem('key')
                                        .then(value => {
                                                       //Operation to do
                                        });
removeItem
This method is to remove the saved value, using its key from AsyncStorage.

                    AsynStorage.removeItem('key', err => {
                             //Operation to do
                    });
clear
This method is to clear the entire AsyncStorage.

                     AsyncStorage.clear();

multiSet
This method is to set multiple (key,values) at same time.

                      let keys = [['name', value1], ['email', value2]];
                     AsyncStorage.multiSet(keys, err =>{
                               // Operation to do
                    });

multiGet
This method is to get multiple stored values at same time.

                 AsyncStorage.multiGet(['key1, key2',...]], err =>{
                               // Operation to do
                  });

multiRemove
This method is to remove multiple stored values at same time.

                  AsyncStorage.multiRemove(['key1, key2',...], err =>{
                               // Operation to do
                  });

Implementation:

Let's see how to implement AsyncStorage in React Native.

Simple get and set:
In this example, let's save the text on AsyncStorage, while typing it using setItem and using getItem, we can get the stored values and set it the fields to display. It will remain same after closing and restarting the app.

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

export default class AsyncStorageExample extends Component {
  state = {
    name: '',
    email: '',
  };
  componentDidMount = () => {
    AsyncStorage.getItem('name').then(value => this.setState({ name: value }));
    AsyncStorage.getItem('email').then(value =>
      this.setState({ email: value })
    );
  };

  setName = value => {
    AsyncStorage.setItem('name', value).then(() => {
      this.setState({ name: value });
    });
  };
  setEmail = value => {
    AsyncStorage.setItem('email', value).then(() => {
      this.setState({ email: value });
    });
  };
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.textInput}
          onChangeText={this.setName}
          placeholder="Enter Name"
        />

        <TextInput
          style={styles.textInput}
          onChangeText={this.setEmail}
          placeholder="Enter Email"
        />
        <Text>
          Name: {this.state.name}
        </Text>
        <Text>
          Email: {this.state.email}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    marginTop: 50,
  },
  textInput: {
    margin: 15,
    height: 35,
    width: 200,
    borderWidth: 1,
    padding: 5,
  },
});

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => AsyncStorageExample);


 

MultiSet, MultiGet, multiRemove:

In this example, let's save the multiple field values at same time using multiSet and get multiple values as multiGet and remove items using multiRemove.

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

export default class AsyncStorageExample extends Component {
  state = {
    name: '',
    email: '',
  };
  componentDidMount = () => {
    this.getValueFromStorage();
  };

  getValueFromStorage = () => {
    let keys = ['name', 'email'];
    AsyncStorage.multiGet(keys).then(result => {
      this.setState({
        name: result[0][1],
        email: result[1][1],
      });
    });
  };

  setName = value => {
    this.setState({ name: value });
  };
  setEmail = value => {
    this.setState({ email: value });
  };

  saveText = () => {
    const value1 = this.state.name;
    const value2 = this.state.email;
    let keys = [['name', value1], ['email', value2]];
    AsyncStorage.multiSet(keys, err => {
      console.log('Value1' + value1 + ' ' + value2);
      this.setState({
        name: value1,
        email: value2,
      });
    });
  };

  clearText = () => {
    let keys = ['name', 'email'];
    AsyncStorage.multiRemove(keys, err => {
      this.getValueFromStorage();
    });
  };
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.textInput}
          placeholder="Enter Name"
          onChangeText={this.setName}
        />

        <TextInput
          style={styles.textInput}
          placeholder="Enter Email"
          onChangeText={this.setEmail}
        />
        <Text>
          Name: {this.state.name}
        </Text>
        <Text>
          Email: {this.state.email}
        </Text>
        <View style={{ flex: 1, flexDirection: 'row' }}>
          <Button title="Clear" color="#841584" onPress={this.clearText} />
          <Button title="Save" color="#841584" onPress={this.saveText} />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    marginTop: 50,
  },
  textInput: {
    margin: 15,
    height: 35,
    width: 200,
    borderWidth: 1,
    padding:5,
  },
});

AppRegistry.registerComponent('AwesomeProject', () => AsyncStorageExample);



That's it!! We have learnt about AsyncStorage now. So let's meet in next post with another interesting topic. Until then, Bubyeee..!!

Comments

  1. This is really best post. Thanks a lot for sharing.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This Information is very attractive & useful.Thank you for share this information: Hire Mobile App Developers in USA

    ReplyDelete
  4. This is really a nice explanation for React
    If your are looking for
    Software Testing boardWrite for us

    ReplyDelete
  5. Hi

    It's a really nice explanation ever seen.

    Keep it up.

    If anyone is looking for the best react native app development company then visit the given link today.

    ReplyDelete
  6. Cool and I have a tremendous give: What House Renovations Need Council Approval home remodeling companies

    ReplyDelete
  7. I have been trying out react native for a while now, and I must say that the concept behind asyncstorage is rather elusive. I would appreciate it if someone could explain it to me as though I am a five-year-old. I've looked into the documentation as well, and still, it does not make sense. On that note, I am looking for such a company that provides the top custom web development services for assistance with a project - does anyone have suggestions?

    ReplyDelete

Post a Comment

Popular posts from this blog

FlatList - PullToRefresh, Load More and Filtering implementation

Showing Alert and Toast - React Native