lecham
lecham

Reputation: 2464

React Navigation: Detect to which screen the app was navigated

I have 2 components:

  1. Dashboard - entry point of the app
  2. Posts

In Dashboard there's an API call in componentDidMount. In Posts component, after receiving posts I navigate to Dashboard. Is it possible to detect if the app was navigated from Posts to Dashboard and remove API call in componentDidMount.

Check the code below:

// Dashboard.js

 componentDidMount() {
   this.handleApiCall(); // default axios get request
// Here I need to detect if the user was navigated to Dashboard from Posts or other component
}


// Posts.js
  handleNavigation = () => {
    this.setState({
      isOpen: false,
    });
      this.props.navigation.navigate('Dashboard');
 };

Thanks!

Upvotes: 3

Views: 514

Answers (1)

AlexZvl
AlexZvl

Reputation: 2302

Try passing the parameters from Posts.js

// Dashboard.js
componentDidMount() {

   const { navigation } = this.props;
   const fromPosts = navigation.getParam('fromPosts', false);
   if(!fromPosts) {
     this.handleApiCall(); // default axios get request
   }

}


// Posts.js
handleNavigation = () => {
    this.setState({
      isOpen: false,
    });

    this.props.navigation.navigate('Dashboard', {fromPosts: true});
 };

Upvotes: 2

Related Questions