removeItem
- React Native course
- Beginner
- Lesson 109/116
- 5 min
Learn to delete data with AsyncStorage.removeItem.
Deleting data with removeItem
AsyncStorage.removeItem is used to delete a specific key and its value. It takes one parameter: the key to delete (string). Since the operation is asynchronous you wait with await. If the key does not exist it does not error; it passes silently.
await AsyncStorage.removeItem('theme');In this example the key 'theme' and its value are deleted. After deletion if you call getItem with the same key you get null. removeItem deletes only one key; to delete all data use AsyncStorage.clear().
Practice Your turn: delete a value with removeItem
Delete the value with AsyncStorage.removeItem('theme'). Use await. The function should be async.
Starter code
import AsyncStorage from '@react-native-async-storage/async-storage';
async function deleteTheme() {
// delete the theme value
}Sample solution
import AsyncStorage from '@react-native-async-storage/async-storage';
async function deleteTheme() {
await AsyncStorage.removeItem('theme');
}Deleting all data
Sometimes you want to delete all data in AsyncStorage at once; for example when the user logs out. For this you use AsyncStorage.clear(). This function takes no parameter and deletes all key-value pairs.
await AsyncStorage.clear();clear should be used carefully; it cannot be undone. If you want to delete only one key removeItem is safer. clear is usually preferred for logout or data reset operations.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does removeItem do?
await AsyncStorage.removeItem('theme')- Reads data
- Deletes a specific key Correct answer
- Deletes all data
- Updates data
Explanation: removeItem deletes a specific key and its value.
2 Fill in the blank: removeItem call
await AsyncStorage.____('theme');
await AsyncStorage.removeItem('theme');
Explanation: You delete a key with removeItem.
3 Match: method and usage
| Term | Meaning |
|---|---|
removeItem |
deletes one key |
clear |
deletes all data |
getAllKeys |
lists all keys |