React-navigation reset explanation

Viewed 985

I've been checking on this for a while and there's a lot of documentation and at the same time, there's nothing. I have problems to invoke the reset method from react-navigation. I have the following StackNavigator

const Routes = StackNavigator({
  Home: { screen: CheckLogin(App), navigationOptions: { header: null } },
  Options: { screen: Options, navigationOptions: { title: 'Settings' } },
  Dashboard: { screen: Dashboard },
});

So the home it could be like a Login, the options is just a single page with some options and the Dashboard is the main page once you're redirected. The point is that on Home, I am checking if I have a previous access token stored, so it goes straightforward to the Dashboard screen. My problem is that it appears the arrow to go back and I don't want that, so a good approach could do a reset of the routes.

In my Dashboard component, I've put inside componentDidMount ( Not sure where to put it otherwise) the following code:

const resetAction = NavigationActions.reset({
      index: 1,
      actions: [
          NavigationActions.navigate({ routeName: 'Home' }),
          NavigationActions.navigate({ routeName: 'Dashboard' })
      ]
    });

      this.props.navigation.dispatch(resetAction);

So what I understood: The actions are the routes that you're available to go, and the index is the one that You want to go inside the positions of the actions array. So position 1 from my actions array is the Dashboard component. This part was a bit confusing from the documentation, so I am not sure.

This code doesn't work. It creates an infinite loop on my app between Home page and Dashboard.

Is there a way that when I get to the Dashboard component, remove the back arrow to replace it for another totally different link?? If the solution is a reset. Could you explain to me what's wrong here and how it really works??

I really appreciate any help.

1 Answers

I think what you want is call this from your Home screen, once you've determined that the user is logged in.

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
      NavigationActions.navigate({ routeName: 'Dashboard' })
  ]
});

  this.props.navigation.dispatch(resetAction);

What this NavigationActions.reset() function is doing is performing the actions specified in the 'actions' key and splicing the resulting state into the navigation history at the specified index (from the 'index' key), and getting rid of all subsequent items in navigation history.

Your available routes are specified in the arguments provided to your navigators, not in the 'actions' key of this argument.

Related