What is AsyncStorage ...
What is AsyncStorage ...
AsyncStorage is an asynchronous, unencrypted, persistent, key-value storage system for React Native applications. It allows developers to store data locally on the device, which can be useful for persisting user preferences, session data, or any other small pieces of information that need to be retained across app sessions.
To use AsyncStorage, you need to install the @react-native-async-storage/async-storage
package. This can be done using npm or yarn:
npm install @react-native-async-storage/async-storage
# or
yarn add @react-native-async-storage/async-storage
After installation, you can import AsyncStorage into your React Native components:
import AsyncStorage from '@react-native-async-storage/async-storage';
To store data, you use the setItem
method. This method takes a key and a value, both of which must be strings. If you need to store objects, you should serialize them using JSON.stringify()
.
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (e) {
// saving error
console.error(e);
}
};
// Example of storing an object
const storeObject = async (key, object) => {
try {
const jsonValue = JSON.stringify(object);
await AsyncStorage.setItem(key, jsonValue);
} catch (e) {
// saving error
console.error(e);
}
};
To retrieve data, you use the getItem
method. This method returns a promise that resolves to the stored value. If the value is an object, you need to parse it using JSON.parse()
.
const getData = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// value previously stored
return value;
}
} catch (e) {
// error reading value
console.error(e);
}
};
// Example of retrieving an object
const getObject = async (key) => {
try {
const jsonValue = await AsyncStorage.getItem(key);
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (e) {
// error reading value
console.error(e);
}
};
To remove a specific item, you use the removeItem
method:
const removeData = async (key) => {
try {
await AsyncStorage.removeItem(key);
} catch (e) {
// remove error
console.error(e);
}
};
To clear all data stored in AsyncStorage, you use the clear
method:
const clearAl...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào