React-Native AsyncStorage
Syntax
AsyncStorage provides a simple asynchronous API to store and retrieve user settings, preferences, and other data in key-value pairs.
import { AsyncStorage } from 'react-native';
// To set a value
AsyncStorage.setItem('key', 'value');
// To get a value
AsyncStorage.getItem('key', (error, result) => {
if (!error) {
console.log(result);
}
});
// To remove a value
AsyncStorage.removeItem('key');
Example
import { AsyncStorage } from 'react-native';
import React, { useState, useEffect } from 'react';
import { Text, View, TextInput } from 'react-native';
const App = () => {
const [name, setName] = useState('');
useEffect(() => {
AsyncStorage.getItem('name').then(value => {
if (value) {
setName(value);
}
});
}, []);
const saveName = () => {
AsyncStorage.setItem('name', name);
};
const removeName = () => {
AsyncStorage.removeItem('name');
};
return (
<View>
<TextInput
value={name}
onChangeText={text => setName(text)}
placeholder="Enter your name"
/>
<Text>Welcome, {name}</Text>
<Button title="Save Name" onPress={saveName} />
<Button title="Remove Name" onPress={removeName} />
</View>
);
};
export default App;
Output
The AsyncStorage.getItem()
and AsyncStorage.removeItem()
methods do not have an output to display in the console. However, the saved data can be retrieved and used in the app as needed.
Explanation
AsyncStorage provides a simple and persistent storage solution for React Native apps. It is an asynchronous API that saves key-value pairs in a local storage database. This data can be retrieved and updated as needed, making it an ideal solution for storing user preferences, settings, and other data that needs to persist beyond a single session.
Use
AsyncStorage can be used to store and retrieve various types of data in a React Native app. This includes simple data types like strings and numbers, as well as complex objects and data structures.
Some common use cases for AsyncStorage include:
- Storing user preferences and settings
- Saving user login information
- Persisting data between sessions
Important Points
- AsyncStorage is limited to storing data of up to 6MB in size.
- AsyncStorage methods are asynchronous and must be handled with callbacks or promises.
- AsyncStorage is a simple key-value store and is not intended for use as a full-fledged database.
Summary
AsyncStorage provides a simple and persistent storage solution for React Native apps. By storing key-value pairs in a local storage database, AsyncStorage allows apps to save and retrieve user preferences, settings, and other data that needs to persist beyond a single session, making it a powerful tool for building robust and user-friendly mobile applications.