How to pop to the previous screen with params?

13,025

Solution 1

I found a good solution is to send a callback function with the params

in screen A

  getback(success)
  {
      alert(success);
  }

  Navigation.push(this.props.componentId , { component : {
         name : "Payment",
         passProps: {
         subscription : current,
         getback: this.getback
       },
   }});

then in screen B , when you pop to screen A fire the getback function

Navigation.pop(this.props.componentId);
this.props.getback(true);

this worked well with me

Solution 2

I have been working on this and I achieved with react-navigation.

Basically, your component A will send to component B the navigation state of component A. So, For B point of view it will be the prevState before stacking B component.

So when component B navigates "back" to component A using the previous navigation state it was like your navigation state never changed and now you could use the second parameter of navigate to send params back to component A.

This simple example illustrate this practice and I think it is totally valid and no AsyncStorage usage.

// In Component A use a custom prevState when goes to Component B
const { navigation } = this.props;

navigation.navigate('ComponentB', { prevState: navigation.state });
// In Component B use this custom goBack to "pop" to last screen
function goBack(data) {
  const { navigation } = this.props;

  const { routeName, key } = navigation.getParam('prevState');

  navigation.navigate({ routeName, key, params: data });
}
// And finally in Component A again you could get data like this
function getDataFromComponentB() {
  const { navigation } = this.props;

  // It is null if no parameters are specified!
  return navigation.state.params;
}
Share:
13,025
Ahmed Mohsen
Author by

Ahmed Mohsen

Updated on June 13, 2022

Comments

  • Ahmed Mohsen
    Ahmed Mohsen almost 2 years

    I'm on screen A which has current state of {key:'value'} , I navigated to screen B

    now I'm trying to pop from screen B to screen A again , but I don't want to lose the current state in screen A {key:'value'}

    some solution is to save data in the AsynStorage , and retrive it when coming back to screen A , but that's not a good practice

    .pop() do it , but what if I need to go back with additional params ?

    Navigation.pop(this.props.componentId , {
                                   passProps: {
                                           data : 'current',
                                           more : 'just-example'
                                         }});
    

    the above code , did not work

    any suggestions ?

    I don't use any state management tool like Redux/Mobx ..