Search code examples
reactjsreact-nativereduxredux-thunk

Redux - how to call an action and wait until it is resolved


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.


Solution

  • 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.