Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React navigation goBack() and update parent state

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

enter image description here

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

enter image description here

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?

like image 673
Darren Lau Avatar asked May 28 '17 04:05

Darren Lau


People also ask

Can we pass params in navigation goBack ()?

Unfortunately, you can not pass data like this when using the goBack() method. One workaround is to pass a callback function to the screen you are navigating to. Then, you can call that function with whatever data you wanted to pass back before calling the goBack() method.

How do you use navigate replace in react?

navigate(to, { state={}, replace=false }) If you need to navigate programmatically (like after a form submits), import navigate . Navigate returns a promise so you can await it. It resolves after React is completely finished rendering the next screen, even with React Suspense.


1 Answers

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(); 
like image 147
Zhang Buzz Avatar answered Sep 22 '22 12:09

Zhang Buzz