Rajan Lagah
Rajan Lagah

Reputation: 2528

How to use componentDidMount on revisiting screen

I have 2 screen.

Screen 1 -> select city -> store in AsyncStorage -> navigate to Screen 2 

In componentDidMount of Screen 2, I am making call to server on the basis of city selected.
problem
componentDidMount fire only at once when i revisit that screen again it will not go to componentDidMount
I searched and learn that Screen 2 is present in stack that is why componentDidMount will not fire again.
So i try this.props.navigation.dispatch(StackActions.popToTop()); and all like this to reset stack but it did not work.
I am not uploading code as i think explanation is sufficient. If required then ask

Upvotes: 0

Views: 123

Answers (1)

Suraj Malviya
Suraj Malviya

Reputation: 3783

Well, you might want to consider to rely on the navigation events provided by the React Navigation (assuming you are using this).

So when you revisit Screen 2, you can make your server call on didFocus event of the navigation lifecycle in Screen 2.

//in ComponentDidMount you should set a listener to the navigation events
const didBlurSubscription = this.props.navigation.addListener(
  'didFocus',
   payload => {
     // Do your API Call here.
   }
);

// Remove the listener when you are done in componentWillUnMount.
didBlurSubscription.remove();

However, I have a doubt here, by revisiting what do you exactly mean ? Are going on some other screen say Screen 3 and coming back using goBack ? If thats the scenerio which i suspect as you say that the Screen2 is in the stack then the solution above might help you.

Upvotes: 1

Related Questions