useFileQueue
An upload queue that runs the state machine and leaves the network to you. Concurrency, cancel, retry, batches, an aggregate progress and one screen-reader summary per upload, wired straight into FileItem and FileUpload.
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.
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 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.
Code
const queue = useFileQueue({ upload, concurrency: 2 });
<Progress value={queue.progress * 100} aria-labelledby="summary" />
<span id="summary">{queue.counts.done} of {queue.entries.length} uploaded</span>
<FileQueueSummary queue={queue} />
<ul>
{queue.entries.map((entry) => (
<FileItem key={entry.id} asChild file={entry.file} {...queue.itemProps(entry.id)}>
<li />
</FileItem>
))}
</ul>
<Button onClick={queue.retryFailed}>Retry failed</Button>
<Button onClick={queue.cancelAll}>Cancel all</Button>
<Button onClick={queue.clear}>Clear uploaded</Button>itemProps(id) gives a FileItem 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).
With FileUpload
Pass the queue to FileUpload 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.
Drop files here or click to browse
Code
const queue = useFileQueue({ upload });
<FileUpload label="Documents" maxFiles={10} queue={queue} />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
| 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
concurrency(default3) 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(defaulttrue) sends files as soon as they are added, which suits a drop-and-go list of attachments. Set it tofalsefor a form where the person picks files first and sends them with a button: added files wait asidleuntilstart().retryable(default: every failure) says whether a failure is worth sending again. See Failures a retry won't fix.onSettledfires once per run, when nothing is left queued or in flight, with the run'sdoneandfailedentries. 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.
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:
progressis 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.countshas the number of entries in each status, over the whole list, plusretryableandpermanent, the failures a retry may fix and the ones it won't.busyistruewhile anything is queued or in flight.
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.
Code
const queue = useFileQueue({
batch: 25,
concurrency: 3,
// A 4xx won't succeed on a retry; a 5xx or a dropped connection may.
retryable: (error) => !(error instanceof HttpError && error.status < 500),
upload: async (files, context) => {
const body = new FormData();
files.forEach((file) => body.append('files', file));
const report = await xhrUpload(url, body, context);
// The request went through, but the server turned some photos away.
files
.filter((file) => report.invalidFiles.includes(file.name))
.forEach((file) => context.fail(file, new HttpError(422, 'No learner has this login.')));
return report;
},
});
queue.reset(); // start over: the last run's failures go too
queue.add(photos);
// One status region for the thousand photos, in the page's own words.
<FileQueueSummary queue={queue} translations={{ summary: photoSummary }} />
// Only the failures are listed: a thousand rows would bury them.
{queue.entries
.filter((entry) => entry.status === 'error')
.map((entry) => (
<FileItem key={entry.id} file={entry.file} thumbnails={false} {...queue.itemProps(entry.id)} />
))}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).
- 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
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:
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, andretryFailed()skips it.itemProps(id)leaves outonRetry, so itsFileItemshows no Retry button: only the message and the ×.counts.retryableandcounts.permanentsplitcounts.errorin two, for copy that says what each button will do:
<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
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.
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);
});
}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:
fetchcan't report upload progress. It reports the response as it arrives, never the request as it leaves. Streaming a request body (fetchwith aReadableStreamandduplex: '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.onprogressreports bytes actually sent, in every browser. A plainfetch(url, { body, signal })still works as a transport:uploadresolves 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 theabortevent rejects the promise with the signal's reason, which the queue ignores. - 100% sent isn't done. Once the last byte is out,
xhr.uploadfires its finalprogressand the server still has work to do (store, scan, resize) before it answers. That's theprocessingstatus: the bar turns indeterminate untilonload. - Upload listeners force a CORS preflight. Registering any listener on
xhr.uploadmakes a cross-origin request non-simple, so the browser sends anOPTIONSrequest first. A backend on another origin must answer it with the rightAccess-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
uploadfunction can drive one internally and report progress through the sameonProgress, but resuming after a reload isn't something the queue keeps track of.
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:
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
- Unmounting aborts every request in flight. Nothing updates after unmount, and
onSettleddoesn'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
fetchin 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
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
onSettledreports. 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 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:
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
- The rows a queue drives don't announce; one
FileQueueSummaryper queue does, as described above. - An aggregate bar is a
Progressnamed after its caption (aria-labelledby), witharia-valuetextfor 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
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:
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 locale (useLocale()), as the demos do. The rows follow the locale's direction.
API
Prop
Type
It returns:
Prop
Type
FileQueueSummary takes:
Prop
Type
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)} />.
useHotkey
Binds a keyboard shortcut, and says where it applies — anywhere, outside or only inside text fields, inside an element, under the pointer — while yielding to overlays opened above it.
useObjectUrl
A URL for a picked or dropped file that's safe to put in an img, video or object, revoked for you, and never one that lets an uploaded file run as your app.