React Native - Navigate after an async action
Asked Answered
I

2

10

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

Intelligencer answered 26/3, 2016 at 16:51 Comment(0)
S
1

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}));
                    }
                }
            );
        }
    }
Stereophotography answered 25/8, 2017 at 12:17 Comment(0)
S
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.

Sidra answered 26/3, 2016 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.