Undo previous async action using redux-thunk

I am building a React / Redux application using redux-thunk middleware to create and process Ajax requests. I have a special tone that is fired quite often, and I would like to cancel any previously launched Ajax requests before starting a new one. Is it possible?

+5
source share
2 answers

One approach would be to mark these requests as canceled by providing them with a random identifier and checking its status before processing the result.

The way to do this is to assign a random identifier for this call in the first dispatch (inside thunk) and check it in the reducer before processing the result.

const actionId = Math.random(); dispatch({type: AJAX_LOAD_CONST, id:actionId }) 

If you want to cancel all requests, use

dispatch({type:HANDLE_AJAX_RESPONSE, id:actionId, results: json })

When you want to process the results, do not forget to send the identifier that you u

and the gearbox has something like this:

 function reducer(state = initialState, action) { switch (action.type) { case actions.AJAX_LOAD_CONST: return Object.assign({}, state, { ajax: state.ajax.concat(action.id) }); case actions.CANCEL_ALL_AJAX: return Object.assign({}, state, { ajax: [] }); case actions.HANDLE_AJAX_RESPONSE: if (state.ajax.includes(action.id) { //return state reduced with action.results here } return state; } } 

If you use XMLHttpRequest or one of its shells (JQuery?), You can also save the queries yourself and call request.abort (). if you use the new fetch api, you do not have this luxury because promises does not have this behavior.

+10
source

You can force your action creator to return the promise, it will be returned by the send function, then you can break it. Here is an example:

Action creator

 function doSomething() { return (dispatch) => { return $.ajax(...).done(...).fail(...); } } 

Your component

  componentDidMount(){ this.previousPromise = this.props.dispatch(doSomething()); } somefnct() { this.previousPromise.abort(); } 
+2
source

All Articles