What is AsyncStorage and how do you use it?
What is AsyncStorage and how do you use it?
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) {
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.