Save and Retrieve Data on the Device in a React Native App with AsyncStorage
We’ll use AsyncStorage to save and load simple text data on the device. AsyncStorage is built into React Native (so it’s easy to get working), but it’s text only, it’s global to your app, and it isn’t built to handle large or complex data. However - it’s perfect for saving and loading small bits of data like settings and configuration values.
Storage
❗Note: This course uses React Native's AsyncStorage, however, this is now deprecated. It is recommended to use the React Native Community Async Storage which needs to be installed from NPM.
🤔AsyncStorage can be used to easily store simple data on the user's device. The API is identical to localStorage on the web, however, it is asynchronous whereas localStorage is synchronous.
Install AsyncStorage from NPM.
npm i @react-native-community/async-storage
Similar to on the web, AsyncStorage's key and value must be strings. We can use the JSON.stringify(...) to turn a JSON object into a string, and JSON.parse(...) to turn a string back into a JSON object.
To write data to localStorage.
import AsyncStorage from '@react-native-community/async-storage';const pokemon = [...] // all 151 pokemonAsyncStorage.setItem('pokemon', JSON.stringify(pokemon)).then(() => { // pokemon have been saved to AsyncStorage })
To read data from localStorage.
import AsyncStorage from '@react-native-community/async-storage';AsyncStorage.getItem('pokemon').then((data) => this.setState({ pokemon: JSON.parse(data) }))
Make sure to protect against null or undefined values when reading or writing AsyncStorage.
if (pokemon) {AsyncStorage.setItem('pokemon', JSON.stringify(pokemon)).then(() => { // pokemon have been saved to AsyncStorage })}
AsyncStorage.getItem('pokemon').then((data) => {if (data) {this.setState({ pokemon: JSON.parse(data) })}})
AsyncStorage is a great way to store simple things - such as user preferences and config - but should not be used in place of a proper database for complex data.