📜  expo asyncstorage - Javascript (1)

📅  最后修改于: 2023-12-03 15:14:57.033000             🧑  作者: Mango

Expo AsyncStorage - Javascript

Expo AsyncStorage is a simple key-value store for storing data in your mobile application. It is a simple and secure way to store data on the client-side in your mobile app. The AsyncStorage API allows you to store and retrieve data stored on the device.

Usage

The AsyncStorage API can be accessed through the expo package. To use it, you need to import the AsyncStorage class from expo:

import { AsyncStorage } from 'react-native';
Setting Data

To set data in the AsyncStorage, use the setItem method. This will store the key and value pair in the AsyncStorage store. Note that the value should be a string.

AsyncStorage.setItem('key', 'value');
Getting Data

To get data from the AsyncStorage, use the getItem method. This will retrieve the value stored for the corresponding key. Note that the returned value will be a string.

const value = await AsyncStorage.getItem('key');
Removing Data

To remove data from the AsyncStorage, use the removeItem method. This will remove the key and its corresponding value from the AsyncStorage store.

AsyncStorage.removeItem('key');
Clearing Data

To clear all data from the AsyncStorage, use the clear method. This will remove all keys and their corresponding values from the AsyncStorage store.

AsyncStorage.clear();
Error Handling

The AsyncStorage API returns a Promise that will resolve to the value of the requested key (if any). If there is an error, it will reject the Promise. You can handle these errors using standard try...catch blocks or by chaining a .catch() method.

try {
  const value = await AsyncStorage.getItem('key');
} catch (error) {
  console.log(error);
}
Security

By default, all data stored in the AsyncStorage is only accessible to the app that created it. However, it is important to be aware that the information stored in the AsyncStorage is not encrypted. Therefore, sensitive information like passwords and API keys should not be stored in AsyncStorage.

Conclusion

Explo AsyncStorage is a simple and straight-forward way to store data on mobile devices using React Native. It is fast, easy to use, and a great way to store data that doesn't need to be encrypted.