Skip to main content

Aborting Fetch

AbortController provides a new way of cancelling fetches that are no longer considered relevant. This can be hooked into fetch via the second RequestInit parameter.

Resource​

Easy integration is provided with the RestEndpoint via the signal member:

const abort = new AbortController();
const AbortableArticle = CoolerArticleResource.get.extend({
signal: abort.signal,
});
// ...somewhere later trigger cancellation
abort.abort();

Endpoint​

Any Endpoint takes a signal member the same way: read this.signal in its fetch function.

Cancelling on params change​

When params change quickly, like a reader skimming an inbox, every message they pass starts a download. Each response is stored under its own params, so a late one never replaces what's on screen. But the downloads they've left behind keep going, sharing a slow connection with the one they actually want.

useCancelling() aborts the in-flight request as soon as the params change, so the message the reader stops on downloads alone.

import { useSuspense, useCancelling } from '@data-client/react';
import { MessageResource } from './resources/Message';

export default function MessageView({ id }: { id: number }) {
  const message = useSuspense(useCancelling(MessageResource.get, { id }), {
    id,
  });
  return (
    <article>
      <h2>{message.subject}</h2>
      <div className="byline">
        <Avatar src={message.from.avatar} size={20} />
        {message.from.name}
      </div>
      {message.body.map((paragraph, i) => (
        <p key={i}>{paragraph}</p>
      ))}
    </article>
  );
}
Live Preview
Warning

Be careful when using this with many disjoint components fetching the same arguments (Endpoint/params pair) to useSuspense(). This solution aborts fetches per-component, which means you might end up canceling a fetch that another component still cares about.