Async Storage can only store string
data. In order to store object data, you need to serialize it first. For data that can be serialized to JSON, you can use JSON.stringify()
when saving the data and JSON.parse()
when loading the data.
import AsyncStorage from '@react-native-async-storage/async-storage';
Storing data
setItem()
is used both to add new data item (when no data for given key exists), and to modify existing item (when previous data for given key exists).
const storeData = async (value) => {
try {
await AsyncStorage.setItem('my-key', value);
} catch (e) {
}
};
Storing object value
const storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value);
await AsyncStorage.setItem('my-key', jsonValue);
} catch (e) {
}
};
Reading data
getItem
returns a promise that either resolves to stored value when data is found for given key, or returns null
otherwise.
const getData = async () => {
try {
const value = await AsyncStorage.getItem('my-key');
if (value !== null) {
}
} catch (e) {
}
};
Reading object value
const getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('my-key');
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (e) {
}
};
More
For more examples, head over to API section.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4