Skip to main content

useCancelling()

Builds an Endpoint that cancels fetch everytime parameters change

Aborts inflight request if the parameters change.

Usage​

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.

It can't abort the first fetch of a component that hasn't rendered yet: React keeps no state for a component that suspends before it mounts. Once the component has shown data, each params change aborts the previous fetch it started. A custom Endpoint must pass this.signal on to its request.

Cancel vs Debounce​

Use useCancelling() when the user stops on each value, like a list they arrow through. It fetches at once and aborts the previous fetch.

Use useDebounce() when the user types. It waits until typing stops, so it sends fewer requests.

For a search, use both:

import {
useCancelling,
useDebounce,
useSuspense,
} from '@data-client/react';
import { searchIssues } from './resources/Issue';

function IssueList({ query }: { query: string }) {
const [q] = useDebounce(query, 200);
const { items } = useSuspense(useCancelling(searchIssues, { q }), { q });
// ...
}

Types​

function useCancelling<
E extends EndpointInterface & {
extend: (o: { signal?: AbortSignal }) => any;
},
>(endpoint: E, ...args: readonly [...Parameters<E>] | readonly [null]): E {