9

I'm developing a mobile app with React Native and Redux and I'm facing a software design problem. I want to call a REST API (async operation) for login and navigate to main view if that operation was successful. I'm using redux and thunk so I already have the async actions implemented so my main doubt is: Where should I put the logic to navigate to main view?

Can I access the navigator object directly from an action and perform the navigation there? Should I do that in the Login Component? (As I'm doing it already - check the code below).

componentWillReceiveProps(nextProps){
    if(nextProps.errorLoginMsg){
        Alert.alert("Login Failed", nextProps.errorLoginMsg);
    }
    else if(!nextProps.user.isNull()){
      this.props.navigator.replace({name: 'main'});
    }
  }

I'm not confident of having that logic in the component. Does not seem a good practice. Are there any other way to do this?

Thanks

user3299310
  • 153
  • 1
  • 7

2 Answers2

0

This is one of the hardest problems in react native with the current Navigator API. I would suggest having a route store which holds the current route and have the component which includes the Navigator connected to this store and having a navigation triggered on componentWillReceiveProps.

Daniel Schmidt
  • 10,316
  • 4
  • 32
  • 63
0

Here is the code how I do it:

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

                this.props.requestDeleteEvent( {
                    id: eventID
                } ).then( () => {
                    this.props.navigation.dispatch( resetAction );
                } );

And inside function requestDeleteEvent:

export function requestDeleteEvent(requestData) {
    const id = requestData.id;

    return (dispatch, getState) => {
        return fetch(Config.event + id, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json; charset=UTF-8',
            },
        })
            .then((response) => getResponseJson(response))
            .then((responseJson) => {
                    if (responseJson.isSuccess) {
                        return dispatch(deleteEvent(id));
                    } 
                    else {
                        return dispatch(triggerToast({type: 'alert', content: ERROR}));
                    }
                }
            );
        }
    }
Tyreal Gray
  • 355
  • 1
  • 7