react-navigation / rfcs

RFCs for changes to React Navigation
Other
88 stars 16 forks source link

Add support to dispatch navigation thunks? #9

Open slorber opened 6 years ago

slorber commented 6 years ago

Hi,

It seems there are cases where you might want to dispatch multiple synchronous navigations. Supporting thunks like does Redux would be helpful to factorise such code.

For example, the code I put in this issue: https://github.com/react-navigation/react-navigation/issues/1715#issuecomment-362368925

export const navigateToRootTab = (navigation,tabName) => {
  const actions = [
    NavigationActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({
          routeName: "Root",
        }),
      ]
    }),
    NavigationActions.navigate({
      routeName: tabName,
    })
  ];
  actions.forEach(navigation.dispatch);
};

The client code is navigateToRootTab(this.props.navigation,"MyTab");

Supporting thunks would allow: The client code is this.props.navigation.dispatch(navigateToRootTab("MyTab"); which looks more natural

This way, we don't have to provide the navigation/dispatch function to the factorised function that dispatch multiple actions

So, to better understand this, are you suggesting to reset asyncronously, wait for the transition to complete, and then perform the second navigation? Or do you expect both actions to happen right away?

@ericvicenti I'm suggesting dispatching multiple actions at once should be made easier by using thunks, not changing the current behavior when dispatching multiple actions which could be discussed in an other issue.

But to answer your question: I would prefer both actions to happen right away in an atomic way.

In my usecase I have a StackNav where initial element is a TabNab. I want to go back to StackNav root, on the 2nd tab. I have to dispatch 2 actions because I am currently unable to do that in a single action. If it did I would only have to dispatch a single action. See the original issue, the following does not work:

NavigationActions.reset({
  index: 0,
  actions: [
    NavigationActions.navigate({
      routeName: "Root", // StackNav root, whose screen is a TabNav
      action: NavigationActions.navigate({
        routeName: tabName, // This does not work, the TabNab is always reset to its initialRouteName
      })
    }),
  ]
});

Notice that I don't know if code above not working is expected or a bug, if the react-navigation library is supposed to always allow setting the nav in an appropriate state with a unique reset action, maybe dispatching multiple actions in a row does not make any sense et thus neither do thunks

Original issue: https://github.com/react-navigation/react-navigation/issues/3402