React Native - AsyncStorage


Advertisements


In this chapter, we will show you how to persist your data using AsyncStorage.

Step 1 - Presentation

In this step, we will create the src/components/home/Home.js file.

import React from 'react'
import AsyncStorageExample from './AsyncStorageExample.js'

const Home = () ⇒ {
   return (
      <AsyncStorageExample />
   )
}
export default Home

Step 2 - Logic

Name from the initial state is empty string. We will update it from persistent storage when the component is mounted.

setName will take the text from our input field, save it using AsyncStorage and update the state.

src/components/home/AsyncStorageExample.js

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

class AsyncStorageExample extends Component {
   state = {
      'name': ''
   }
   componentDidMount = () ⇒ AsyncStorage.getItem('name').then((value) 
      ⇒ this.setState({ 'name': value }))

   setName = (value) ⇒ {
      AsyncStorage.setItem('name', value);
      this.setState({ 'name': value });
   }
   render() {
      return (
         <View style = {styles.container}>
            <TextInput style = {styles.textInput} autoCapitalize = 'none' 
               onChangeText = {this.setName}/>
            <Text>
               {this.state.name}
            </Text>
         </View>
      )
   }
}
export default AsyncStorageExample

const styles = StyleSheet.create ({
   container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 50
   },
   textInput: {
      margin: 15,
      height: 35,
      borderWidth: 1,
      backgroundColor: '#7685ed'
   }
})

When we run the app, we can update the text by typing into the input field.

React Native Async Storage

To check if the data is persistent, we can just reload the simulator. The text will still be visible.

React Native Async Storage 2

Advertisements