# useFileQueue (/docs/hooks/use-file-queue)





`useFileQueue` runs uploads for you: a few at a time, each one cancellable, with a retry when one fails and a progress bar for the lot. It never makes a request. You pass `upload`, the function that sends one file, and the queue decides when to call it and tracks what happens to the file.

```tsx
import { useFileQueue } from '@42-central/ui-react';
import { FileItem } from '@42-central/ui-react/file-item';
import { FileQueueSummary } from '@42-central/ui-react/file-queue-summary';

const queue = useFileQueue({
  upload: (file, { signal, onProgress }) => send(file, { signal, onProgress }),
});

queue.add(files);

<FileQueueSummary queue={queue} />
{queue.entries.map((entry) => (
  <FileItem key={entry.id} file={entry.file} {...queue.itemProps(entry.id)} />
))}
```

`upload` gets the file and two tools: a `signal`, aborted when the file is cancelled, and `onProgress(loaded, total)`, to call as the bytes go out. Resolve once the server has the file, reject if it doesn't. A transport built on `XMLHttpRequest` does both; see [A real transport](#a-real-transport-xmlhttprequest).

## A queue [#a-queue]

The demo's uploads are fake: the bytes go out at a fixed rate and the "server" takes a moment to answer. Two run at a time. `transcript.pdf` drops at 60% on its first try, and any other file may fail at random. Add the samples, cancel one while it uploads, then retry the failures.

<Preview align="block" code="&#x22;const queue = useFileQueue({ upload, concurrency: 2 });\n\n<Progress value={queue.progress * 100} aria-labelledby=\&#x22;summary\&#x22; />\n<span id=\&#x22;summary\&#x22;>{queue.counts.done} of {queue.entries.length} uploaded</span>\n\n<FileQueueSummary queue={queue} />\n<ul>\n  {queue.entries.map((entry) => (\n    <FileItem key={entry.id} asChild file={entry.file} {...queue.itemProps(entry.id)}>\n      <li />\n    </FileItem>\n  ))}\n</ul>\n\n<Button onClick={queue.retryFailed}>Retry failed</Button>\n<Button onClick={queue.cancelAll}>Cancel all</Button>\n<Button onClick={queue.clear}>Clear uploaded</Button>&#x22;">
  <FileQueueDemo />
</Preview>

`itemProps(id)` gives a [`FileItem`](/docs/file-item) everything about one upload: its `status`, `progress` and `error`, plus `onCancel`, `onRemove` and `onRetry`. The row's × cancels while the file is queued or in flight and removes it once it has settled, and its accessible name says which ("Cancel upload of cv.pdf", then "Remove cv.pdf"). The rows don't announce their uploads: `FileQueueSummary` speaks for the whole upload instead (see [What screen readers hear](#what-screen-readers-hear)).

## With FileUpload [#with-fileupload]

Pass the queue to [`FileUpload`](/docs/file-upload) and the dropzone, the list and the uploads work together: each file you drop is added to the queue, and its row shows its upload. `FileUpload` renders the queue's `FileQueueSummary` itself.

<Preview align="block" code="&#x22;const queue = useFileQueue({ upload });\n\n<FileUpload label=\&#x22;Documents\&#x22; maxFiles={10} queue={queue} />&#x22;">
  <FileQueueUploadDemo />
</Preview>

The list is the queue's, so `queue` replaces `value`; passing both is a compile error. `onChange` still fires with the files. In a single-file `FileUpload`, picking a new file replaces the old one, and the old upload is aborted.

## How a file moves [#how-a-file-moves]

| Status       | What it means                                                                                                                                  |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `idle`       | Added with `autoStart: false`, waiting for `start()`.                                                                                          |
| `queued`     | Waiting for a free slot.                                                                                                                       |
| `uploading`  | `upload` is running. `progress` is `undefined` until `onProgress` is first called, so the bar shows as indeterminate rather than stuck at 0%.  |
| `processing` | Every byte is sent (`loaded` reached `total`), and the promise hasn't settled yet: the server is still storing, scanning or resizing the file. |
| `done`       | The promise resolved. `result` holds what it resolved with.                                                                                    |
| `error`      | The promise rejected. `error` holds what it rejected with, and `retryable` whether a retry may fix it.                                         |

**A cancelled file is removed**, rather than kept with a `cancelled` status. Cancelling is the person saying they don't want that file sent, so a row that stays behind would only be one more thing to dismiss, and a status `FileItem` would have to explain. To send it after all, they add it again.

`cancel` and `remove` both drop the file and abort its upload, with one difference: `cancel` only acts on a file that is queued or in flight. A click on "Cancel upload" that lands just as the upload finishes then leaves the finished file alone instead of throwing it away.

To start over, `reset()` aborts every request in flight and empties the list in one go, failures included; `clear()` only drops the files that are done. The batch demo's button resets before adding the next thousand photos.

Once the queue has aborted a request, nothing that request does afterwards counts: a late resolve, a late rejection (the `AbortError` your transport throws), a last progress event. Each one is checked against the request the file belongs to now.

## Options [#options]

* **`concurrency`** (default `3`) is how many requests run at once, never more. One upload rarely fills an uplink, so a few in parallel finish sooner, but browsers allow only six connections per host over HTTP/1.1, and the page needs some of them for its own requests. Lower it if your server limits uploads per user.
* **`autoStart`** (default `true`) sends files as soon as they are added, which suits a drop-and-go list of attachments. Set it to `false` for a form where the person picks files first and sends them with a button: added files wait as `idle` until `start()`.
* **`retryable`** (default: every failure) says whether a failure is worth sending again. See [Failures a retry won't fix](#failures-a-retry-wont-fix).
* **`onSettled`** fires once per run, when nothing is left queued or in flight, with the run's `done` and `failed` entries. A run is every file queued since the queue was last idle; cancelled files are in neither list. It is the place for a toast: say how many failed rather than calling it a success.

```tsx
const queue = useFileQueue({
  upload,
  autoStart: false,
  onSettled: ({ done, failed }) =>
    failed.length > 0
      ? notify.error(`${failed.length} of ${done.length + failed.length} files failed.`)
      : notify.success(`${done.length} files uploaded.`),
});

<Button onClick={queue.start} disabled={queue.counts.idle === 0}>Upload</Button>
```

The aggregates follow the queue:

* `progress` is the current run's bytes sent over its bytes to send, from 0 to 1. A settled file counts in full, failed ones included: the bar measures how much is left to do, so it reaches the end. A new run starts it again from 0.
* `counts` has the number of entries in each status, over the whole list, plus `retryable` and `permanent`, the failures a retry may fix and the ones it won't.
* `busy` is `true` while anything is queued or in flight.

## Batches: 1000 photos, 25 per request [#batches-1000-photos-25-per-request]

Some endpoints take several files in one request. Bulk-uploading student photos is one: up to a thousand photos, sent 25 per request, with the server answering which ones it couldn't match to a learner. Set `batch` and `upload` receives up to that many files at once.

<Preview align="block" code="&#x22;const queue = useFileQueue({\n  batch: 25,\n  concurrency: 3,\n  // A 4xx won't succeed on a retry; a 5xx or a dropped connection may.\n  retryable: (error) => !(error instanceof HttpError && error.status < 500),\n  upload: async (files, context) => {\n    const body = new FormData();\n    files.forEach((file) => body.append('files', file));\n    const report = await xhrUpload(url, body, context);\n    // The request went through, but the server turned some photos away.\n    files\n      .filter((file) => report.invalidFiles.includes(file.name))\n      .forEach((file) => context.fail(file, new HttpError(422, 'No learner has this login.')));\n    return report;\n  },\n});\n\nqueue.reset(); // start over: the last run's failures go too\nqueue.add(photos);\n\n// One status region for the thousand photos, in the page's own words.\n<FileQueueSummary queue={queue} translations={{ summary: photoSummary }} />\n\n// Only the failures are listed: a thousand rows would bury them.\n{queue.entries\n  .filter((entry) => entry.status === 'error')\n  .map((entry) => (\n    <FileItem key={entry.id} file={entry.file} thumbnails={false} {...queue.itemProps(entry.id)} />\n  ))}&#x22;">
  <FileQueueBulkDemo />
</Preview>

In the demo, the sixth request fails on its first try (a 502) and every 97th photo has no matching learner. The 502's 25 photos can be retried; the ten unmatched ones need fixing (see [Failures a retry won't fix](#failures-a-retry-wont-fix)).

* The request's progress is split across its files by size, so each file and the aggregate bar move together.
* A request that **rejects** fails every file in it. Retrying puts them back in line, and they go out in the next batch.
* A request that **resolves** marks its files done, except the ones `context.fail(file, reason)` named: the server took the request but turned those files away. They are failures like any other, with your reason as their message.
* **Cancelling one file of a batch** aborts the whole request, since a file can't leave a request already on the way, and puts the batch's other files back in line. They go out again without it.

`batch` is the only change: the same queue, the same statuses, and the same `itemProps`. It isn't a recipe on top of the single-file queue, because a recipe would have to bypass the queue's own abort and progress tracking to group files, and would get both wrong for the files it left out.

## Failures a retry won't fix [#failures-a-retry-wont-fix]

Some failures are about the file, not the network. The photo endpoint answers `invalidFiles: ["dupont_j.jpg"]` because no learner has that login, the app calls `fail(file, …)`, and Retry would send the same bytes to get the same answer, forever. `retryFailed()` would too, so the failed count would never reach zero. A dropped connection or a 503 looks just the same from the row, and for those Retry is exactly right.

`retryable` tells them apart. It is given what `upload` rejected with, or what a batch's `fail` was given, and says whether sending the file again might work:

```tsx
class HttpError extends Error {
  constructor(readonly status: number, message: string) {
    super(message);
  }
}

const queue = useFileQueue({
  batch: 25,
  retryable: (error) => !(error instanceof HttpError && error.status < 500),
  upload: async (files, context) => {
    const report = await xhrUpload(url, toFormData(files), context); // rejects with an HttpError
    files
      .filter((file) => report.invalidFiles.includes(file.name))
      .forEach((file) => context.fail(file, new HttpError(422, 'No learner has this login.')));
    return report;
  },
});
```

A failure it turns down stays `error`, with its message, and its entry has `retryable: false`:

* `retry(id)` does nothing for it, and `retryFailed()` skips it.
* `itemProps(id)` leaves out `onRetry`, so its `FileItem` shows no Retry button: only the message and the ×.
* `counts.retryable` and `counts.permanent` split `counts.error` in two, for copy that says what each button will do:

```tsx
<h3>{counts.error} failed</h3>
{counts.retryable > 0 && <Button onClick={queue.retryFailed}>Retry {counts.retryable}</Button>}
{counts.permanent > 0 && <span>{counts.permanent} need fixing</span>}
```

The fix for a permanent failure is outside the queue: address its cause (create the learner, rename the photo to the right login), then drop the corrected file. It is a new entry with its own upload, and the old one can be removed with its ×. Without `retryable`, every failure is retryable.

## A real transport: XMLHttpRequest [#a-real-transport-xmlhttprequest]

The kit doesn't ship a transport: your app knows its API, its auth and its errors. This one is a starting point. Copy it into your app.

```ts title="xhr-upload.ts"
import type { FileQueueUploadContext } from '@42-central/ui-react';

type Init = {
  method?: 'POST' | 'PUT';
  headers?: Record<string, string>;
  /** Send cookies cross-origin. */
  withCredentials?: boolean;
};

/** Sends `body` with real upload progress, and aborts when the queue's signal does. */
export function xhrUpload<T>(
  url: string,
  body: XMLHttpRequestBodyInit,
  { signal, onProgress }: FileQueueUploadContext,
  { method = 'POST', headers = {}, withCredentials = false }: Init = {},
): Promise<T> {
  return new Promise((resolve, reject) => {
    if (signal.aborted) return reject(signal.reason);
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.responseType = 'json';
    xhr.withCredentials = withCredentials;
    Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));

    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) onProgress(event.loaded, event.total);
    };
    xhr.onload = () =>
      xhr.status >= 200 && xhr.status < 300
        ? resolve(xhr.response)
        : reject(new Error(xhr.response?.message ?? `The server answered ${xhr.status}.`));
    xhr.onerror = () => reject(new Error('The connection dropped. Try again.'));
    xhr.onabort = () => reject(signal.reason);
    signal.addEventListener('abort', () => xhr.abort(), { once: true });

    xhr.send(body);
  });
}
```

```tsx
const queue = useFileQueue({
  upload: (file, context) => {
    const body = new FormData();
    body.append('file', file);
    return xhrUpload<StoredDocument>('/api/documents', body, context);
  },
});
```

What to know about it:

* **`fetch` can't report upload progress.** It reports the response as it arrives, never the request as it leaves. Streaming a request body (`fetch` with a `ReadableStream` and `duplex: 'half'`) only works in Chromium-based browsers, only over HTTP/2 or later, and counting the chunks you hand the stream measures what the browser has buffered, not what reached the network. `xhr.upload.onprogress` reports bytes actually sent, in every browser. A plain `fetch(url, { body, signal })` still works as a transport: `upload` resolves at the end, and the bar stays indeterminate meanwhile.
* **The signal maps to `xhr.abort()`.** The queue aborts the signal when the file is cancelled or removed, or when the component unmounts. `xhr.abort()` closes the connection, and the `abort` event rejects the promise with the signal's reason, which the queue ignores.
* **100% sent isn't done.** Once the last byte is out, `xhr.upload` fires its final `progress` and the server still has work to do (store, scan, resize) before it answers. That's the `processing` status: the bar turns indeterminate until `onload`.
* **Upload listeners force a CORS preflight.** Registering any listener on `xhr.upload` makes a cross-origin request non-simple, so the browser sends an `OPTIONS` request first. A backend on another origin must answer it with the right `Access-Control-Allow-*` headers, or every upload fails before it starts. A same-origin endpoint, or a proxy path on your app's own origin, needs nothing.
* **Cancelling only stops the client.** Aborting closes the connection, but a server that already received the whole file may still store it. If a cancelled file must not exist, have the server discard incomplete uploads, or delete it afterwards.
* **Resumable and chunked uploads are out of scope.** The queue retries a file from its first byte. Uploads that resume where they stopped (tus, S3 multipart) need a protocol on both ends; an `upload` function can drive one internally and report progress through the same `onProgress`, but resuming after a reload isn't something the queue keeps track of.

### Presigned URLs [#presigned-urls]

To send a file straight to object storage, ask your API for a presigned URL, then `PUT` the file itself (not a `FormData`) to it:

```ts
const queue = useFileQueue({
  upload: async (file, context) => {
    const { url, key } = await api.presign(
      { name: file.name, type: file.type, size: file.size },
      { signal: context.signal },
    );
    await xhrUpload(url, file, context, { method: 'PUT', headers: { 'Content-Type': file.type } });
    // Still `processing` here: the file is stored, the app just doesn't know it yet.
    return api.confirm(key, { signal: context.signal });
  },
});
```

The `Content-Type` must match the one the URL was signed for, and the bucket's CORS rules must allow `PUT` from your origin, preflight included.

## Strict Mode, unmounting, the server [#strict-mode-unmounting-the-server]

* **Unmounting aborts every request in flight.** Nothing updates after unmount, and `onSettled` doesn't fire for an abandoned run.
* **Strict Mode** rehearses an unmount in development: the requests it aborts are sent again on the remount, the way a `fetch` in an effect would be. Your transport sees the first ones aborted.
* **On the server** the queue is empty and sends nothing; requests start after mount.
* Entry ids are stable for an entry's life and unique within the queue: use them as React keys.

## What screen readers hear [#what-screen-readers-hear]

One upload is one conversation. A queue of 400 photos at three requests at a time would make each row announce its start and its end, about 800 announcements talking over each other, with the failures lost among them. So the rows a queue drives keep quiet, and one polite `role="status"` region, `FileQueueSummary`, speaks for the run:

| When                   | It says                                                                   |
| ---------------------- | ------------------------------------------------------------------------- |
| A run starts           | "Uploading 400 files"                                                     |
| While it runs          | nothing                                                                   |
| Files fail             | "2 files failed: a.jpg, b.jpg", or "12 files failed" past three names     |
| The run settles        | "Upload finished: 388 uploaded, 12 failed" (no failed part when none did) |
| `cancelAll` or `reset` | "Upload stopped"                                                          |
| A one-file run ends    | "report.pdf uploaded", or "report.pdf failed: The file is too large."     |

* **A run** starts when the queue goes from not busy to busy, and ends when nothing is left queued or in flight. It is the same run `onSettled` reports. A file added or retried while it runs joins it: the total grows, and there is no second "Uploading…".
* **It settles** when its files have all settled, and **is stopped** when it ends because files still waiting were dropped: `cancelAll()`, `reset()`, or cancelling the last file in flight.
* **Failures are said as they happen**, not saved for the end: a person can act on them while the rest uploads. Failures within about a second of the first are gathered into one sentence, so a request of 25 photos failing at once is one announcement, not 25. Any still gathering when the run ends are said just before "Upload finished", never after it.
* The region is in the page from the first render, empty. A live region that appears already filled may go unread (VoiceOver skips it), so don't mount it conditionally.

[`FileUpload`](/docs/file-upload) renders one when it has a `queue`. For a list of your own, render it once, next to the rows. It is visually hidden (`sr-only`), so keep it inside a positioned element:

```tsx
import { FileQueueSummary } from '@42-central/ui-react/file-queue-summary';

<div className="relative">
  <FileQueueSummary queue={queue} />
  {queue.entries.map((entry) => (
    <FileItem key={entry.id} file={entry.file} {...queue.itemProps(entry.id)} />
  ))}
</div>
```

`itemProps` passes `announce: false`, which is what keeps the rows quiet. A `FileItem` you feed yourself, outside a queue, keeps its own announcements. To have a queue-driven row speak anyway, pass `announce` after the spread.

## Accessibility [#accessibility]

* The rows a queue drives don't announce; one `FileQueueSummary` per queue does, as described above.
* An aggregate bar is a [`Progress`](/docs/progress) named after its caption (`aria-labelledby`), with `aria-valuetext` for the percentage. Its value isn't announced as it moves, which is what you want: a screen reader user reads it on demand.
* For a bulk upload, don't render a row per file: list only the failures, as the batch demo does. A thousand rows bury the few that need attention.
* Say how many failed. A run that ends with failures is never a success toast.

## In another language [#in-another-language]

The hook has no strings of its own. The rows' strings go through `FileItem`'s `translations`, or `FileUpload`'s, which carries the same keys (`cancel`, `retry`, `queued`, `processing`, `done`, `failed`). The summary has one key, `summary(event)`, on `FileQueueSummary`'s `translations` and on `FileUpload`'s. It gets the event and returns the sentence:

```tsx
const number = new Intl.NumberFormat(useLocale());
const fichiers = (n: number) => (n === 1 ? '1 fichier' : `${number.format(n)} fichiers`);

const summary = ({ phase, total, done, failed, names, reason }: FileQueueSummaryEvent) =>
  match(phase)
    .with('start', () => (total === 1 ? `Envoi de ${names[0]}` : `Envoi de ${fichiers(total)}`))
    .with('failed', () =>
      names.length === 1
        ? `Échec de ${names[0]}${reason ? ` : ${reason}` : ''}`
        : `Échec de ${fichiers(names.length)}${names.length <= 3 ? ` : ${names.join(', ')}` : ''}`,
    )
    .with('settled', () =>
      total === 1
        ? failed > 0 ? `Échec de ${names[0]}${reason ? ` : ${reason}` : ''}` : `${names[0]} envoyé`
        : `Envoi terminé : ${number.format(done)} envoyés${failed > 0 ? `, ${number.format(failed)} en échec` : ''}`,
    )
    .with('stopped', () => 'Envoi interrompu')
    .exhaustive();

<FileQueueSummary queue={queue} translations={{ summary }} />
```

The event is `{ phase, total, done, failed, names, reason? }`. `phase` is `"start"`, `"failed"`, `"settled"` or `"stopped"`. `total`, `done` and `failed` count the run's files. `names` are the files the sentence is about: the run's files when it starts, the ones that just failed, the failed ones when it ends, and in a one-file run that one file. `reason` is the failure's message when the sentence is about one failed file. Plurals are yours to get right: the English default only tells one from many.

Format your own counts and percentages with `Intl.NumberFormat` and the [`IntlProvider`](/docs/intl) locale (`useLocale()`), as the demos do. The rows follow the locale's direction.

## API [#api]

<TypeTable
  type="{
  upload: {
    type: '(file: File, context) => Promise<R>',
    required: true,
    description: 'Sends one file. context is { signal, onProgress(loaded, total) }. With batch, receives File[] and a context with fail(file, reason?) too.',
  },
  batch: { type: 'number', description: 'Up to this many files per request.' },
  concurrency: { type: 'number', default: '3', description: 'Requests in flight at once.' },
  autoStart: { type: 'boolean', default: 'true', description: 'Send files as soon as they are added. Off, they wait as idle until start().' },
  retryable: { type: '(error: unknown) => boolean', default: '() => true', description: &#x22;Whether a failure (a rejection, or a batch's fail) is worth sending again. Turned down, it stays failed with retryable: false, and no Retry is offered.&#x22; },
  onSettled: { type: '({ done, failed }) => void', description: 'Fires once per run, when nothing is left queued or in flight.' },
}"
/>

It returns:

<TypeTable
  type="{
  entries: { type: 'FileQueueEntry<R>[]', description: '{ id, file, status, progress, loaded, total, error, retryable, result }, in the order they were added.' },
  byId: { type: 'Map<string, FileQueueEntry<R>>', description: 'The entries by id.' },
  progress: { type: 'number', description: &#x22;The current run's bytes sent over its bytes, from 0 to 1. A settled file counts whole.&#x22; },
  counts: { type: 'Record<FileQueueStatus, number> & { retryable; permanent }', description: 'Entries per status, and the failures split into the ones a retry may fix and the ones it won\'t.' },
  busy: { type: 'boolean', description: 'Something is queued or in flight.' },
  add: { type: '(files: File | File[] | FileList) => string[]', description: 'Adds files and returns their ids.' },
  start: { type: '() => void', description: 'Sends every idle file.' },
  cancel: { type: '(id: string) => void', description: 'Aborts a queued or in-flight file and drops it. A settled file is left alone.' },
  remove: { type: '(id: string) => void', description: 'Drops a file, aborting its upload if it is in flight.' },
  cancelAll: { type: '() => void', description: 'Cancels every queued and in-flight file.' },
  retry: { type: '(id: string) => void', description: &#x22;Sends a failed file again. Does nothing for one that isn't retryable.&#x22; },
  retryFailed: { type: '() => void', description: &#x22;Sends every failed file again, skipping the ones that aren't retryable.&#x22; },
  clear: { type: '() => void', description: 'Drops the files that are done.' },
  reset: { type: '() => void', description: 'Starts over: aborts every request in flight and empties the list. An abandoned run never reaches onSettled.' },
  itemProps: { type: '(id: string) => FileQueueItemProps', description: &#x22;A FileItem's status, progress, error, onCancel, onRemove and onRetry (left out when the failure isn't retryable) for one entry, and announce: false.&#x22; },
}"
/>

`FileQueueSummary` takes:

<TypeTable
  type="{
  queue: { type: 'FileQueue', required: true, description: 'The queue to speak for. It reads entries and busy.' },
  translations: { type: '{ summary?: (event: FileQueueSummaryEvent) => string }', description: 'The sentence for each event. See In another language.' },
  className: { type: 'string', description: 'On the region, which is sr-only.' },
  testId: { type: 'string', description: 'data-testid on the region.' },
}"
/>

`error` in `itemProps` is the message of the `Error` your transport rejected with (or the string it rejected with), so write it for the person reading it. Anything else leaves `FileItem` its own "Upload failed". Pass `error` after the spread to map it yourself: `<FileItem {...queue.itemProps(id)} error={describe(entry.error)} />`.
