Summary - Async Storage
- React Native course
- Beginner
- Lesson 111/116
- 5 min
Combine setItem, getItem and JSON to write a settings system.
Summary - Async Storage
In this group you learned persistent data storage. You write values with AsyncStorage.setItem, read with getItem and delete with removeItem. All operations are asynchronous; you wait with await.
To store objects you convert them to strings with JSON.stringify and convert back with JSON.parse when reading. Now let us combine these concepts in exercises.
Practice Your turn: save a value with setItem
Save a language value by calling AsyncStorage.setItem('lang', 'tr'). Use await. The function should be async.
Starter code
import AsyncStorage from '@react-native-async-storage/async-storage';
async function saveLang() {
// save the lang value
}Sample solution
import AsyncStorage from '@react-native-async-storage/async-storage';
async function saveLang() {
await AsyncStorage.setItem('lang', 'tr');
}Practice Your turn: read and parse JSON
Read the string with AsyncStorage.getItem('user') and convert it to an object with JSON.parse. Return the result.
Starter code
import AsyncStorage from '@react-native-async-storage/async-storage';
async function loadUser() {
// read string and convert to object
return null;
}Sample solution
import AsyncStorage from '@react-native-async-storage/async-storage';
async function loadUser() {
const raw = await AsyncStorage.getItem('user');
return JSON.parse(raw);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does getItem return?
await AsyncStorage.getItem('k')- An array
- A component
- Always a number
- A Promise (value or null) Correct answer
Explanation: getItem returns a Promise; it resolves to a value or null.
2 Match: method and role
| Term | Meaning |
|---|---|
setItem |
write value |
getItem |
read value |
removeItem |
delete value |