React Native course · Module 9: Data storage
AsyncStorage - Simple storage
In this lesson3
Welcome to the Triton Archive! Learn how to store data locally.
Installation
npx expo install @react-native-async-storage/async-storageBasic operations
import AsyncStorage from '@react-native-async-storage/async-storage';
// Save
await AsyncStorage.setItem('username', 'Poseidon');
// Save object (JSON)
const user = { id: 1, name: 'Poseidon', level: 99 };
await AsyncStorage.setItem('user', JSON.stringify(user));
// Read
const username = await AsyncStorage.getItem('username');
const userData = await AsyncStorage.getItem('user');
const user = userData ? JSON.parse(userData) : null;
// Remove
await AsyncStorage.removeItem('username');
// Multiple keys
await AsyncStorage.multiSet([['key1', 'value1'], ['key2', 'value2']]);
const values = await AsyncStorage.multiGet(['key1', 'key2']);
// All keys
const allKeys = await AsyncStorage.getAllKeys();
// Clear everything
await AsyncStorage.clear();useStorage Hook
function useStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(initialValue);
const [loading, setLoading] = useState(true);
useEffect(() => {
AsyncStorage.getItem(key).then((stored) => {
if (stored) setValue(JSON.parse(stored));
setLoading(false);
});
}, [key]);
const setStoredValue = async (newValue: T) => {
setValue(newValue);
await AsyncStorage.setItem(key, JSON.stringify(newValue));
};
return [value, setStoredValue, loading] as const;
}
// Usage
const [settings, setSettings, loading] = useStorage('settings', { theme: 'dark' });Code for this lesson: App.tsx
import React, { useState, useEffect } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
// Hook for persistent data storage in AsyncStorage
function useStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(initialValue);
const [loading, setLoading] = useState(true);
useEffect(() => {
// TODO: read the saved value via AsyncStorage.getItem(key)
// TODO: if it exists, set it via setValue(JSON.parse(stored))
// TODO: finally call setLoading(false)
}, [key]);
const setStoredValue = async (newValue: T) => {
setValue(newValue);
// TODO: save the new value via AsyncStorage.setItem(key, JSON.stringify(newValue))
};
return [value, setStoredValue, loading] as const;
}
export default function App() {
const [settings, setSettings] = useStorage('settings', { theme: 'dark' });
return (
<View style={styles.container}>
<Text style={styles.text}>Theme: {settings.theme}</Text>
<Pressable
style={styles.button}
onPress={() => setSettings({ theme: settings.theme === 'dark' ? 'light' : 'dark' })}
>
<Text style={styles.buttonText}>Toggle theme</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1a5276',
},
text: {
fontSize: 20,
color: '#fff',
marginBottom: 16,
},
button: {
paddingVertical: 12,
paddingHorizontal: 24,
borderRadius: 8,
backgroundColor: '#2980b9',
},
buttonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How to install AsyncStorage?
2. How to save a value in AsyncStorage?
These are 2 of 7 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange value retrieval:
- Click in order
Click the multiSet elements:
- Code editor
Complete the code of the useStorage custom hook.