Kurs React Native · Moduł 9: Przechowywanie danych
AsyncStorage - Proste przechowywanie
W tej lekcji3
Witaj w Archiwum Trytona! Naucz się przechowywać dane lokalnie.
Instalacja
npx expo install @react-native-async-storage/async-storagePodstawowe operacje
import AsyncStorage from '@react-native-async-storage/async-storage';
// Zapis
await AsyncStorage.setItem('username', 'Posejdon');
// Zapis obiektu (JSON)
const user = { id: 1, name: 'Posejdon', level: 99 };
await AsyncStorage.setItem('user', JSON.stringify(user));
// Odczyt
const username = await AsyncStorage.getItem('username');
const userData = await AsyncStorage.getItem('user');
const user = userData ? JSON.parse(userData) : null;
// Usuwanie
await AsyncStorage.removeItem('username');
// Wiele kluczy
await AsyncStorage.multiSet([['key1', 'value1'], ['key2', 'value2']]);
const values = await AsyncStorage.multiGet(['key1', 'key2']);
// Wszystkie klucze
const allKeys = await AsyncStorage.getAllKeys();
// Wyczyść wszystko
await AsyncStorage.clear();Hook useStorage
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;
}
// Użycie
const [settings, setSettings, loading] = useStorage('settings', { theme: 'dark' });Kod do tej lekcji: 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 do trwałego przechowywania danych w AsyncStorage
function useStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(initialValue);
const [loading, setLoading] = useState(true);
useEffect(() => {
// TODO: pobierz zapisaną wartość przez AsyncStorage.getItem(key)
// TODO: jeśli istnieje, ustaw ją przez setValue(JSON.parse(stored))
// TODO: na końcu ustaw setLoading(false)
}, [key]);
const setStoredValue = async (newValue: T) => {
setValue(newValue);
// TODO: zapisz nową wartość przez 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}>Motyw: {settings.theme}</Text>
<Pressable
style={styles.button}
onPress={() => setSettings({ theme: settings.theme === 'dark' ? 'light' : 'dark' })}
>
<Text style={styles.buttonText}>Zmień motyw</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',
},
});Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jak zainstalować AsyncStorage?
2. Jak zapisać wartość w AsyncStorage?
To 2 z 7 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Układanie w poziomie
Ułóż pobieranie wartości:
- Klikanie w kolejności
Kliknij elementy multiSet:
- Edytor kodu
Uzupełnij kod custom hooka useStorage.