# Aborting Fetch

[AbortController](https://developer.mozilla.org/en-US/docs/Web/API/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](https://dataclient.io/rest/api/RestEndpoint.md) via the signal member:

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

## Endpoint

Any [Endpoint](https://dataclient.io/rest/api/Endpoint.md#signal) 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()](https://dataclient.io/docs/api/useCancelling.md) aborts the in-flight request as soon as the params change, so
the message the reader stops on downloads alone.

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