3

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.

2
  • check dev.to/bil/… Commented Jul 6, 2020 at 11:31
  • 2
    Also, you may be looking for debouncing your function Commented Jul 6, 2020 at 11:32

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.