This app lets you type your name and save it on the phone. When you open the app again, it shows the saved name.
import React, { useState, useEffect } from 'react';
import { View, Text, Button, TextInput } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
export default function App() {
const [name, setName] = useState('');
const [storedName, setStoredName] = useState('');
useEffect(() => {
async function loadName() {
try {
const value = await AsyncStorage.getItem('name');
if (value !== null) {
setStoredName(value);
}
} catch (e) {
// error reading value
}
}
loadName();
}, []);
const saveName = async () => {
try {
await AsyncStorage.setItem('name', name);
setStoredName(name);
setName('');
} catch (e) {
// saving error
}
};
return (
<View style={{ padding: 20 }}>
<Text>Enter your name:</Text>
<TextInput
value={name}
onChangeText={setName}
placeholder="Your name"
style={{ borderWidth: 1, marginVertical: 10, padding: 5 }}
/>
<Button title="Save Name" onPress={saveName} />
{storedName ? <Text style={{ marginTop: 20 }}>Saved name: {storedName}</Text> : null}
</View>
);
}