6

I am using the abortcontroller to cancel a fetch request inside a custom react hook as shown below:

useEffect(() => {
    const controller = new AbortController();
    const { signal } = controller;
    const fetchData = async () => {
      try {
        setState({ status: 'pending', data: null, error: null });
        const response = await fetch(url, {
          signal,
          ...options,
        });

        // if response is an HTTP error like 4XX 5XX
        if (!response.ok) {
          throw new Error(response.statusText);
        }
        // if response is 2XX
        const data = (await response.json()) as T;
        setState({ status: 'resolved', data, error: null });
      } catch (error) {
        setState({ status: 'rejected', data: null, error: error as Error });
      }
    };
    fetchData();
    return () => {
      controller.abort(); // abort!
    };
}, [url, options]);

Click to see live in CodeSandbox

When I try to hit multiple requests one after the other, I can see it cancels all my previous requests which is expected but when I revisit the same requests again there it doesn't cancel for the 2nd time.

enter image description here

We can see in the screenshot above while changing the IDs quickly using the up arrow from ID 10 to 24 we see all the intermediate requests are canceled successfully but when moving back using the down arrow, all the intermediate requests are hit and not canceled this time.

Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93
  • I thought an AbortController could only send its signal once (although I can find no mention of that now). Does it work if you create a new controller for the second run? – Tom Feb 08 '22 at 21:06
  • Does this answer your question? [How can I start another request after AbortController.abort()?](https://stackoverflow.com/questions/51091109/how-can-i-start-another-request-after-abortcontroller-abort) – Tom Feb 08 '22 at 21:07

0 Answers0