Search code examples
react-native-navigationwix-react-native-navigation

Push a screen as a result of a redux action


Recently tried https://wix.github.io/react-native-navigation/v2/#/ As I understand one of the problems solved in v2 was pushing a screen as a result of a redux action. Basically I am still having doubts which is the right way to use navigator outside component.

export function loginUser(user, componentId) {
  return async (dispatch) => {
    dispatch({ type: ActionTypes.LOGIN_PENDING })

    Api.loginUser(user)
      .then((response) => {
        // success
        Navigation.push(componentId, { component: { name: 'Profile' }})

      })
      .catch((err) => {
        dispatch({
          type: ActionTypes.LOGIN_ERROR,
          payload: { ...err.response.data, status: err.response.status },
        })
      })
  }
}

Passing componentId kinda feels weird to me. How you guys do it? Suggestions appreciated!


Solution

  • To push a screen from outside of the stack's scope - You first need to assign the stack a predefined id, then you can easily push to it from your actions by passing the stack's id, instead of some componentId you propagate to your actions from a component.

    First, assign an id to your stack:

    const stack = {
      id: 'MyStack', // This will allow you to interact with the stack from your actions
      children: [
        {
          component: {}
        },
        {
          component: {}
        }
      ],
      options: {
    
      }
    }
    

    Then, push your screen to the stack associated with MyStack id:

    Navigation.push('MyStack', {
      component: {
        name: 'MyComponent'
      }
    });