6

I'm using react native + redux + redux-thunk I do not have much experience with redux and react native

I'm calling an action inside my component.

this.props.checkClient(cliente);

if(this.props.clienteIsValid){
   ...
}

and within that action there is a call to an api that takes a few seconds.

export const checkClient = (cliente) => {
    return dispatch => {

        axios.get(`${API_HOST}/api/checkclient`, header).then(response => {

            dispatch({type: CHECK_CLIENT, payload: response.data }); //valid or invalid

        }).catch((error) => {  });

    }
}

My question is how can I delay the return of the action until the api response is completed? I need the api response to know if the client is valid or invalid. That is, I need the action to be resolved and then verify that the client is valid or invalid.

Jobsdev
  • 967
  • 3
  • 9
  • 27

3 Answers3

8

You can return a promise from the action, so that the call becomes thenable:

// Action
export const checkClient = (cliente) => {
    return dispatch => {
        // Return the promise
        return axios.get(...).then(res => {
            ...
            // Return something
            return true;
        }).catch((error) => {  });
    }
}


class MyComponent extends React.Component {

    // Example
    componentDidMount() {
        this.props.checkClient(cliente)
            .then(result => {
                // The checkClient call is now done!
                console.log(`success: ${result}`);

                // Do something
            })
    }
}

// Connect and bind the action creators
export default connect(null, { checkClient })(MyComponent);

This might be out of scope of the question, but if you like you can use async await instead of then to handle your promise:

async componentDidMount() {
    try {
        const result = await this.props.checkClient(cliente);
        // The checkClient call is now done!
        console.log(`success: ${result}`)

        // Do something
    } catch (err) {
        ...
    }
}

This does the same thing.

micnil
  • 4,053
  • 1
  • 25
  • 31
1

I don't understand the problem, but maybe this could help

export const checkClient = (cliente) => {
  return dispatch => {
    dispatch({type: CHECK_CLIENT_PENDING });

    axios.get(`${API_HOST}/api/checkclient`, header).then(response => {

        dispatch({type: CHECK_CLIENT, payload: response.data }); //valid or invalid

    }).catch((error) => {  });

   }
}

...


 this.props.checkClient(cliente);

 if(this.props.clienteIsPending){
  ...
 }

 if(this.props.clienteIsValid){
  ...
 }
Yasin Tazeoglu
  • 427
  • 4
  • 9
0

I have written a full code if there is still confusion. The promise should work for a sequence of asynchronous redux action calls

Actions

export const buyBread = (args) => {
  return dispatch => {
    return new Promise((resolve, reject) => {

        dispatch({type: BUY_BREAD_LOADING });
        // or any other dispatch event

        // your long running function
       
        dispatch({type: BUY_BREAD_SUCCESS, data: 'I bought the bread'});
        // or any other dispatch event

        // finish the promise event
        resolve();

        // or reject it
        reject();
    
    });
}

export const eatBread = (args) => {
  return dispatch => {
    return new Promise((resolve, reject) => {

        dispatch({type: EAT_BREAD_LOADING });
        // or any other dispatch event

        // your long running function
       
        dispatch({type: EAT_BREAD_SUCCESS, data: 'I ate the bread'});
        // or any other dispatch event

        // finish the promise event
        resolve();

        // or reject it
        reject();
    
    });
}

Reducer

const initialState = {}
export const actionReducer = (state = initialState, payload) => {
    switch (payload.type) {
        case BUY_BREAD_LOADING:
           return { loading: true };
        case BUY_BREAD_SUCCESS:
           return { loading: false, data: payload.data };
        case EAT_BREAD_LOADING:
           return { loading: true };
        case EAT_BREAD_SUCCESS:
           return { loading: false, data: payload.data };
}

Component class

import React, {Component} from 'react';

class MyComponent extends Component {
    render() {
        return (
            <div>
                <button onClick={()=>{
                    this.props.buyBread().then(result => 
                        this.props.eatBread();
                        // to get some value in result pass argument in resolve() function
                    );
                }}>I am hungry. Feed me</button>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    actionReducer: state.actionReducer,
});

const actionCreators = {
    buyBread: buyBread,
    eatBread: eatBread
};

export default connect(mapStateToProps, actionCreators)(MyComponent));
bikram
  • 3,748
  • 29
  • 39