Introduction
AsyncStorage lets you save small pieces of data on the phone. This helps keep information even after the app closes.
AsyncStorage lets you save small pieces of data on the phone. This helps keep information even after the app closes.
import AsyncStorage from '@react-native-async-storage/async-storage'; // Save data await AsyncStorage.setItem('key', 'value'); // Read data const value = await AsyncStorage.getItem('key'); // Remove data await AsyncStorage.removeItem('key');
await AsyncStorage.setItem('username', 'Alice');
const username = await AsyncStorage.getItem('username');
await AsyncStorage.removeItem('username');
This app lets you type your name and save it on the phone. When you open the app again, it shows the saved name.
import React, { useState, useEffect } from 'react'; import { View, Text, Button, TextInput } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; export default function App() { const [name, setName] = useState(''); const [storedName, setStoredName] = useState(''); useEffect(() => { async function loadName() { try { const value = await AsyncStorage.getItem('name'); if (value !== null) { setStoredName(value); } } catch (e) { // error reading value } } loadName(); }, []); const saveName = async () => { try { await AsyncStorage.setItem('name', name); setStoredName(name); setName(''); } catch (e) { // saving error } }; return ( <View style={{ padding: 20 }}> <Text>Enter your name:</Text> <TextInput value={name} onChangeText={setName} placeholder="Your name" style={{ borderWidth: 1, marginVertical: 10, padding: 5 }} /> <Button title="Save Name" onPress={saveName} /> {storedName ? <Text style={{ marginTop: 20 }}>Saved name: {storedName}</Text> : null} </View> ); }
AsyncStorage is good for small data only, not big files or databases.
Always handle errors to avoid app crashes.
Data saved is persistent until removed or app is uninstalled.
AsyncStorage stores key-value pairs on the device.
Use async/await to save, read, and remove data.
Great for saving user settings and small info.
AsyncStorage in React Native?setItem, which returns a promise and requires await.save, store, and put do not exist in AsyncStorage API.import AsyncStorage from '@react-native-async-storage/async-storage';
async function test() {
await AsyncStorage.setItem('name', 'Alice');
const value = await AsyncStorage.getItem('name');
console.log(value);
}
test();import AsyncStorage from '@react-native-async-storage/async-storage';
function saveData() {
AsyncStorage.setItem('token', 'abc123');
console.log('Token saved');
}
saveData();removeItem, which returns a promise and should be awaited.getItem returns null, confirming deletion.Pass the test and this pattern moves unknown