Issue
I've a page that will render the user's name if s/he is logged in or "Create an account" or "Sign in" option if s/he not. Screen as below
They can navigate to "Sign in" or "Create an account" page. After successfully signing in or registering, it will navigate to this page and it will show the user name. Screen as below
Currently, I store user data in AsyncStorage
, I want to update this field once the user successfully logs in or register when they redirect from the page.
How can I achieve this?
is there a way to pass param from navigate.goBack()
and parent can listen to the params and update its state?
Solution
You can pass a callback function as parameter when you call navigate like this:
const DEMO_TOKEN = await AsyncStorage.getItem('id_token');
if (DEMO_TOKEN === null) {
this.props.navigation.navigate('Login', {
onGoBack: () => this.refresh(),
});
return -3;
} else {
this.doSomething();
}
And define your callback function:
refresh() {
this.doSomething();
}
Then in the login/registration view, before goBack, you can do this:
await AsyncStorage.setItem('id_token', myId);
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack();
Update for React Navigation v5:
await AsyncStorage.setItem('id_token', myId);
this.props.route.params.onGoBack();
this.props.navigation.goBack();
Answered By - Zhang Buzz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.