# useCancelling()

Builds an Endpoint that cancels fetch everytime parameters change

[Aborts](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) inflight request if the parameters change.

## Usage

```ts title="resources/Message"
import { Entity, resource, validateRequired } from '@data-client/rest';

/** What the inbox lists */
export class MessageSummary extends Entity {
  id = 0;
  from = { name: '', avatar: '' };
  subject = '';

  static key = 'Message';
}

/** The whole message, once opened */
export class Message extends MessageSummary {
  body: string[] = [];

  // a summary in the store isn't the whole message: fetch it
  static validate(processedEntity: any) {
    return validateRequired(processedEntity, this.defaults);
  }
}

export const MessageResource = resource({
  urlPrefix: 'https://api.example.com',
  path: '/messages/:id',
  schema: Message,
}).extend({
  getList: { schema: [MessageSummary] },
});
```

```tsx title="MessageView" {5}
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>
  );
}
```

```tsx title="Inbox"
import React from 'react';
import { AsyncBoundary, useSuspense } from '@data-client/react';
import { MessageResource } from './resources/Message';
import MessageView from './MessageView';

export default function Inbox() {
  const messages = useSuspense(MessageResource.getList);
  const [openId, setOpenId] = React.useState(messages[0].id);
  return (
    <>
      <header className="appHeader">
        <h1 className="appTitle">Inbox</h1>
      </header>
      <div className="split">
        <div className="list">
          {messages.map(message => (
            <button
              key={message.pk()}
              className="listItem"
              aria-current={message.id === openId}
              onClick={() => setOpenId(message.id)}
            >
              <Avatar src={message.from.avatar} />
              <div>
                <h4>{message.from.name}</h4>
                <small>{message.subject}</small>
              </div>
            </button>
          ))}
        </div>
        <AsyncBoundary
          fallback={<Loading />}
          errorComponent={ErrorMessage}
        >
          <MessageView id={openId} />
        </AsyncBoundary>
      </div>
    </>
  );
}
render(<Inbox />);
```

> **Warning: 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](https://dataclient.io/rest/api/Endpoint.md#members-not-args) 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()](https://dataclient.io/docs/api/useDebounce.md) when the user types. It waits until typing stops, so it sends
fewer requests.

For a search, use both:

```tsx
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

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