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

强颜欢笑 提交于 2019-12-07 12:04:16

问题


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.


回答1:


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.




回答2:


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){
  ...
 }


来源:https://stackoverflow.com/questions/54054887/redux-how-to-call-an-action-and-wait-until-it-is-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!