React Native - AsyncStorage

In questo capitolo, ti mostreremo come mantenere i tuoi dati usando AsyncStorage.

Passaggio 1: presentazione

In questo passaggio, creeremo il file App.js file.

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

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

Passaggio 2: logica

Namedallo stato iniziale è una stringa vuota. Lo aggiorneremo dalla memoria persistente quando il componente sarà montato.

setName prenderà il testo dal nostro campo di input, lo salverà usando AsyncStorage e aggiorna lo stato.

async_storage_example.js

import React, { Component } from 'react'
import { StatusBar } from 'react-native'
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: 5,
      height: 100,
      borderWidth: 1,
      backgroundColor: '#7685ed'
   }
})

Quando eseguiamo l'app, possiamo aggiornare il testo digitandolo nel campo di input.