Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Navigate after an async action

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

like image 799
user3299310 Avatar asked May 03 '26 14:05

user3299310


1 Answers

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}));
                    }
                }
            );
        }
    }
like image 166
Tyreal Gray Avatar answered May 06 '26 10:05

Tyreal Gray