Subscribe now

Persisting data in React Native [11.17.2016]

Probably you will need to store some data locally in your phone.

React Native API has AsyncStorage which is a super simple, unencrypted, asynchronous, persistent, key-value storage system. Let's see the documentation: https://facebook.github.io/react-native/docs/asyncstorage.html

As you can see, the three important methods are: - GetItem - SetItem - RemoveItem

Names are self-explanatory. Let's see this working. We are going to create a screen with your name and phone and then we will save this. Let's also have a button to clean the database. For testing, we will write something, close the app and open it again. We will do it first time without persistence, second time with persistence and then you will see that we are really persisting the data.

Let's create a view. We are going to create two TextInput, one for name and other for phone, two buttons, one for reset the database and other for save.

We will have in our state name and phone. As I would like to show how the state changes when filling out the field, I'm going to create a state for phone and name, furthermore I would like to show the state when we are persisting with this we can directly see what is persisted, we will create a persitedName and persistedAge.

      <View style={styles.container}>
        <Text style={gstyles.title}>
          Persisting Data
        </Text>

      <Text>Name</Text>
      <TextInput
       value={this.state.name}
       onChangeText={(text) => this.setState({name: text})}
       style={styles.input} />

       <Text>Phone</Text>
       <TextInput
       value={this.state.phone}
       onChangeText={(text) => this.setState({phone: text})}
       style={styles.input} />

        <TouchableHighlight
          style={styles.button}
          onPress={this.persistData}
          underlayColor="white">
          <Text style={styles.buttonText}> SAVE </Text>
        </TouchableHighlight>

        <TouchableHighlight
          style={styles.button}
          onPress={this.clearData}
          underlayColor="white">
          <Text style={styles.buttonText}> CLEAR </Text>
        </TouchableHighlight>

        <View>
          <Text>STATE:</Text>
          <Text>Name: {this.state.name}</Text>
          <Text>Phone: {this.state.phone}</Text>
        </View>

        <View>
          <Text>PERSISTENCE DATA:</Text>
          <Text>Name: {this.state.persistedName}</Text>
          <Text>Phone: {this.state.persistedPhone}</Text>
        </View>

      </View>

For clearing data, I'm using the method clear from AsyncStorage. Here I'm clearing everything on AsyncStorage. I could just delete the keys we were using, but here I'm using the method clear for the sake of learning, just to simplify things.

  clearData(){
    AsyncStorage.clear();
    this.setState({persistedPhone: '', persistedName: ''})
  }

We already have buttons, fields and the clear function. Let's create the function which we will insert everything.

  persistData(){
    let name = this.state.name
    let phone = this.state.phone
    AsyncStorage.setItem('name', name).done();
    AsyncStorage.setItem('phone', phone).done();
    this.setState({name: name, persistedName: name, phone: phone, persistedPhone: phone })
  }

Here we are using the method setItem for phone and name as we thought. Also, we are updating our state, this will reflect in our views, we have two Text fields where we are showing the current state.

We need to check once the app starts what we have persisted. To do that, we'll use the componentWillMount method which is the ideal for what we think, because if we set the update in this method, the render method will be called just one time.

Here we are getting the stored items and updating just the state concerned to the persistence.

check(){

    AsyncStorage.getItem('name').then((name) => {
        this.setState({name: name, persistedName: name})
    })

    AsyncStorage.getItem('phone').then((phone) => {
      this.setState({phone: phone, persistedPhone: phone})
    })
  }

  componentWillMount(){
    this.check();
  }

You may do a simple exercise:

Without persistence: (you can just comment the persistence code. There is one tag called without-persistence which you can use)

  • Create the screen;
  • Show the name on the screen;
  • Close the app;
  • Open the app. Name is not there;

With Persistence:

  • Implement the persistence part;
  • Type the name;
  • Show the name on the screen;
  • Close the app;
  • Name is there;

That's it! See you soon!

Code: https://github.com/dailydrip/react-native-persisting-data/releases/tag/persistence-functionality

Resources