I have a situation where I need to do an API request on each character change of input in react. When I type 3 letters 3 API requests are triggering. But there is no order of finishing the requests. Most of the time my last request is finishing first and then the old requests. As per my requirements, I want to cancel any previous calls before a new API call.
I found a way to cancel the previous request and accept only the response from the latest request. I am using redux-thunk as the middleware. I can use a controller as AbortController and send a signal to the fetch request and then I can cancel the previous request using this controller.
return (dispatch, getState, serviceManager) => {
const { controller } = getState();
controller.abort(); //cancel the previous request
let newController = new AbortController();
let signal = newController.signal;
//set a new AbortController instance to the reducer
dispatch({type: "SET_NEW_CONTROLLER", payload: newController})
//pass the signal to the fetch request
const result = await fetch(url, {...options, signal});
}
you can store a instance of AbortController in the reducer and beginning of the request you can simply abort the controller and set the new controller to the reducer and pass the signal to the fetch request.