Reputation: 21
I am trying to get AsyncStorage on B screen from A screen. On A screen i am saving them and getting them on B, but problem seems to be like that when i navigate to screen b i only get the values when i refresh B screen. It works fine in Expo but in emulator it doesn't.
Please have a look at my code :
import React from 'react';
import { Button, View, Text, TextInput, TouchableOpacity } from 'react-native';
import { styles } from './styles';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import AsyncStorage from '@react-native-async-storage/async-storage';
function HomeScreen({ navigation }) {
const [email, setEmail] = React.useState('');
const redirect = (emailAddress) => {
storeData(emailAddress);
navigation.navigate('Details');
};
const storeData = async (emailAddress) => {
try {
await AsyncStorage.setItem('email', emailAddress);
} catch (e) {
console.log('Error Saving Data', e);
}
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<TextInput
style={styles.input}
value={email}
onChangeText={(email) => setEmail(email)}
placeholder="Enter email address here"
placeholderTextColor="rgba(62, 88, 112, 0.5)"
keyboardType="email-address"
underlineColorAndroid={'transparent'}
autoCapitalize="none"
/>
<TouchableOpacity style={{ margin: 20 }} onPress={() => redirect(email)}>
<Text style={styles.registerText}> Register</Text>
</TouchableOpacity>
</View>
);
}
function DetailsScreen() {
const [text, setText] = React.useState('');
React.useEffect(() => {
const getEmail = async () => {
try {
const email = await AsyncStorage.getItem('email');
if (email !== null) {
setText(email);
}
} catch (e) {
console.log(' error : ' + e);
}
};
getEmail();
}, []);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen : {text}</Text>
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Please help me solve this.
Upvotes: 1
Views: 81
Reputation: 2106
Solution:
To make the details page get the value correctly you need to set the value and wait for it to set in your home page before navigating to details screen so you can get it in the next screen.
const redirect = async (emailAddress) => {
await storeData(emailAddress);
navigation.navigate('Details');
};
Better Solution:
First of all, you don't need to store email in your asyncStorage and retrieve it in the details you can pass it as a route param like this:
navigation.navigate('Details', {email});
and in your details screen:
function DetailsScreen({route}) {
const {email} = route.parmas;
...
}
Upvotes: 2