Ankit Kumar
Ankit Kumar

Reputation: 138

How to refresh a component which is already present in stack after navigating from another component in react native

Ex- I have two components A and B. I need to refresh component A after navigating from component B.

componentDid Mount doesn't work because A is already mounted.

How to achieve this. I am using react navigation to navigate from B->A

Upvotes: 3

Views: 1076

Answers (2)

Dhaval Jardosh
Dhaval Jardosh

Reputation: 7309

You can either use NavigationEvents from react-navigation or can pass a callback which will trigger on navigation.goBack().

Check this snack : Temporary Link

Upvotes: 4

abhikumar22
abhikumar22

Reputation: 1814

You can add a listener for the same in react native.

There are total 4 listners for the same.

  1. willFocus - the screen will focus
  2. didFocus - the screen focused (if there was a transition, the transition completed)
  3. willBlur - the screen will be unfocused
  4. didBlur - the screen unfocused (if there was a transition, the transition completed)


Try the below code

componentDidMount(){
    const didFocusSubscription = this.props.navigation.addListener(
      'didFocus',
      payload => {
        console.warn('didFocus ', payload);
        # just write your code/call a method here which you want to execute when the app comes from a component
        this.handleRefresh()
      }
    );
}

Dont forget to remove it when it is done.

componentWillMount(){
    didFocusSubscription.remove();
}

More you can read here. Thanks :)

Upvotes: 2

Related Questions