AsyncStorage
is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.
It is recommended that you use an abstraction on top of AsyncStorage
instead of AsyncStorage
directly for anything more than light usage since it operates globally.
Please read more about it here
Here's an example React Native code for implementing AsyncStorage:
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const STORAGE_KEY = '@MyApp:key';
const AsyncStorageExample = () => {
const [value, setValue] = useState('');
const handleSave = async () => {
try {
await AsyncStorage.setItem(STORAGE_KEY, value);
console.log('Value saved successfully');
} catch (e) {
console.error('Error saving value:', e);
}
};
const handleLoad = async () => {
try {
const value = await AsyncStorage.getItem(STORAGE_KEY);
if (value !== null) {
setValue(value);
console.log('Value loaded successfully');
}
} catch (e) {
console.error('Error loading value:', e);
}
};
useEffect(() => {
handleLoad();
}, []);
return (
<View style={{ padding: 20 }}>
<Text>Enter a value:</Text>
<TextInput
style={{ borderWidth: 1, borderColor: 'gray', padding: 10, marginVertical: 10 }}
value={value}
onChangeText={setValue}
/>
<Button title="Save" onPress={handleSave} />
</View>
);
};
export default AsyncStorageExample;
In this example, we are creating a simple component that allows the user to enter a value and save it to AsyncStorage
. We define a constant STORAGE_KEY
to use as the key for the saved value.
We define a value
state variable to hold the current value entered by the user, and we provide a TextInput
component for the user to enter the value. We also define a handleSave
function that uses the AsyncStorage.setItem
method to save the value to AsyncStorage
when the user clicks the "Save" button.
We define a handleLoad
function that uses the AsyncStorage.getItem
method to load the saved value from AsyncStorage
when the component is mounted. We call this function in a useEffect
hook with an empty dependency array to ensure that it is only called once when the component is mounted.
Finally, we render the TextInput
and "Save" button, and we pass the value
and setValue
state variables to the TextInput
component to allow the user to update the value.