AsyncStorage is a key-value storage system that lets you store data persistently.
npm install @react-native-async-storage/async-storage
import AsyncStorage from '@react-native-async-storage/async-storage';
// Save data
AsyncStorage.setItem('key', 'value')
.then(() => console.log('Data saved successfully'))
.catch((error) => console.error('Error saving data:', error));
// Retrieve data
AsyncStorage.getItem('key')
.then((value) => console.log('Value:', value))
.catch((error) => console.error('Error retrieving data:', error));
// Remove data
AsyncStorage.removeItem('key')
.then(() => console.log('Data removed successfully'))
.catch((error) => console.error('Error removing data:', error));
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, AsyncStorage, StyleSheet } from 'react-native';
const AsyncStorageExample = () => {
const [inputText, setInputText] = useState('');
const [storedData, setStoredData] = useState('');
useEffect(() => {
// Load stored data on component mount
loadData();
}, []);
const saveData = async () => {
try {
// Save data to AsyncStorage
await AsyncStorage.setItem('@MyApp:storedData', inputText);
console.log('Data saved successfully!');
} catch (error) {
console.error('Error saving data:', error);
}
};
const loadData = async () => {
try {
// Load data from AsyncStorage
const data = await AsyncStorage.getItem('@MyApp:storedData');
if (data !== null) {
setStoredData(data);
console.log('Data loaded successfully!');
}
} catch (error) {
console.error('Error loading data:', error);
}
};
return (
<View style={styles.container}>
<Text style={styles.label}>Enter text to save:</Text>
<TextInput
style={styles.input}
onChangeText={(text) => setInputText(text)}
value={inputText}
/>
<Button title="Save" onPress={saveData} />
<Text style={styles.label}>Stored Data:</Text>
<Text style={styles.storedData}>{storedData}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
label: {
fontSize: 16,
marginBottom: 5,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginBottom: 10,
padding: 10,
width: '100%',
},
storedData: {
marginTop: 10,
fontSize: 18,
fontWeight: 'bold',
},
});
export default AsyncStorageExample;
This example shows how to save a login token, retrieve it during app launch, and use it to log the user in automatically. Make sure your actual server-side API call and logic replaces the token validity check.
import AsyncStorage from '@react-native-community/async-storage';
const STORAGE_KEY = '@myapp:token';
const storeToken = async (token) => {
try {
await AsyncStorage.setItem(STORAGE_KEY, token);
console.log('Token successfully stored');
} catch (error) {
console.error('Error storing token:', error);
}
};
const retrieveToken = async () => {
try {
const token = await AsyncStorage.getItem(STORAGE_KEY);
return token;
} catch (error) {
console.error('Error retrieving token:', error);
return null;
}
};
const checkLogin = async () => {
const token = await retrieveToken();
if (token) {
// Check token validity on your server here
// Replace with your actual API call and logic
const isValid = await fetch('/api/verify-token', { headers: { Authorization: `Bearer ${token}` } });
if (isValid) {
// Redirect to logged-in screen
return true;
} else {
// Token expired, remove it and redirect to login
await AsyncStorage.removeItem(STORAGE_KEY);
return false;
}
} else {
// No token found, redirect to login
return false;
}
};
export default function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() => {
async function handleLoginCheck() {
const loggedIn = await checkLogin();
setIsLoggedIn(loggedIn);
}
handleLoginCheck();
}, []);
// Render components based on isLoggedIn state
if (isLoggedIn) {
// Render logged-in user interface
} else {
// Render login screen
}
}