- React Native Tutorial
- React Native - Home
- Core Concepts
- React Native - Overview
- React Native - Environment Setup
- React Native - App
- React Native - State
- React Native - Props
- React Native - Styling
- React Native - Flexbox
- React Native - ListView
- React Native - Text Input
- React Native - ScrollView
- React Native - Images
- React Native - HTTP
- React Native - Buttons
- React Native - Animations
- React Native - Debugging
- React Native - Router
- React Native - Running IOS
- React Native - Running Android
- Components and APIs
- React Native - View
- React Native - WebView
- React Native - Modal
- React Native - ActivityIndicator
- React Native - Picker
- React Native - Status Bar
- React Native - Switch
- React Native - Text
- React Native - Alert
- React Native - Geolocation
- React Native - AsyncStorage
- React Native Useful Resources
- React Native - Quick Guide
- React Native - Useful Resources
- React Native - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
React Native - AsyncStorage
In this chapter, we will show you how to persist your data using AsyncStorage.
Step 1: Presentation
In this step, we will create the App.js file.
import React from 'react' import AsyncStorageExample from './async_storage_example.js' const App = () => { return ( <AsyncStorageExample /> ) } export default App
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.
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' } })
When we run the app, we can update the text by typing into the input field.
Advertisements