Queue
An outbox that sends messages one at a time, in the order you queued them. Each send takes 1.5 seconds, so you have time to pause the queue, stop it, start it again or remove a message that has not been sent yet.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://dummyjson.com" });
type Message = { title: string; userId: number };
/**
* `queued: true` sends requests of this queue one at a time, in the order they were added.
* A fixed `queryKey` names the queue, so `useQueue` and every `submit()` refer to the same one.
* `delay` makes each send take 1.5 s, which leaves time to pause, stop or remove messages.
*/
export const sendMessageRequest = client
.createRequest<{
response: Message & { id: number };
payload: Message;
queryParams: { delay: number };
}>()({
endpoint: "/posts/add",
method: "POST",
queued: true,
queryKey: "outbox",
})
.setQueryParams({ delay: 1500 });
npx tiged BetterTyped/hyper-fetch/examples/react/queue hyper-fetch-react-queue && cd hyper-fetch-react-queue && npm install && npm run devqueued: true: requests in the same queue run one after another instead of in parallel.useQueuelists the queued requests and returnsstart,pauseandstopfor the whole queue.- Per-request control: each item has
deleteRequest,stopRequestandstartRequest. keepFinishedRequestskeeps sent messages in the list as a history.
How it works
-
sendMessageRequestis aPOSTwithqueued: trueand a fixedqueryKey: "outbox". The dispatcher keeps one queue perqueryKey, and the fixed key makes sure every message and theuseQueuehook use the same queue. -
queueMessage()callssubmit({ payload })fromuseSubmit. Each call adds a request at the end of the queue. The dispatcher sends the next one only when the previous one is finished. -
useQueue(sendMessageRequest, { keepFinishedRequests: true })returns the queue asrequests, itsstoppedstate and the controls:const { requests, stopped, start, pause, stop } = useQueue(sendMessageRequest, {keepFinishedRequests: true,}); -
Pause stops the queue but lets the message being sent finish. Stop also aborts it; the aborted message stays in the queue, marked
canceled, and is sent again after Start. -
Each item carries flags (
success,failed,canceled,removed,stopped) thatgetStatus()turns into a label.dispatcher.hasRunningRequest()tells which message is being sent right now. -
Remove calls
item.deleteRequest(), which takes the message out of the queue and aborts it if it is running.
- Chat messages, comments or form steps that must reach the server in order.
- Several uploads that should not compete for bandwidth.
- Work the user should be able to hold back, for example while editing an item that is still waiting.
Related
queued: true makes requests with the same queryKey run one at a time. useQueue shows that queue and lets you
start, pause and stop it, or remove single requests.
