setItem
- React Native course
- Beginner
- Lesson 107/116
- 5 min
Learn to write data with AsyncStorage.setItem.
Writing data with setItem
AsyncStorage.setItem is used to write a value to a key. It takes two parameters: the key (string) and the value (string). Since the operation is asynchronous you must wait with await. The function is called inside an async function.
await AsyncStorage.setItem('theme', 'dark');In this example the value 'dark' is written to the key 'theme'. If you call setItem on the same key again the old value is overwritten. The value must always be a string; to write a number convert it: String(42).
Async operations
AsyncStorage operations are asynchronous; that is, they do not finish the moment they are called. The result is returned as a Promise. You wait for the operation to complete with the await keyword. Therefore the setItem call is always inside an async function.
async function saveTheme() {
await AsyncStorage.setItem('theme', 'dark');
}If you do not use await the operation continues in the background; but the rest of the function runs without waiting. This can cause the data to be read before it is written. At the beginner level you should always use await.
Practice Your turn: save a value with setItem
Save a value by calling AsyncStorage.setItem('theme', 'dark'). Use await. The function should be async.
Starter code
import AsyncStorage from '@react-native-async-storage/async-storage';
async function saveTheme() {
// save the theme value
}Sample solution
import AsyncStorage from '@react-native-async-storage/async-storage';
async function saveTheme() {
await AsyncStorage.setItem('theme', 'dark');
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: setItem call
await AsyncStorage.____('theme', 'dark');
await AsyncStorage.setItem('theme', 'dark');
Explanation: You write a value with setItem.
2 What does setItem return?
await AsyncStorage.setItem('k', 'v')- It returns the written value
- It returns a component
- It returns an array
- It returns a Promise Correct answer
Explanation: setItem returns a Promise; you wait with await.
3 Match: parameter and role
| Term | Meaning |
|---|---|
first parameter |
key |
second parameter |
value |
await |
waiting |