React navigation goBack() and update parent state

Darren Lau picture Darren Lau · May 28, 2017 · Viewed 99k times · Source

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?

Answer

Zhang Buzz picture Zhang Buzz · May 28, 2017

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();