Dispatcher
A Dispatcher decides when a request goes out. Every send() adds the request to a queue named by its queryKey,
where the dispatcher applies deduplication, cancelation, one-by-one ordering, offline handling and retries before the
adapter runs. A client has two: fetchDispatcher for GET and QUERY requests and submitDispatcher for everything else.
- Runs requests from queues, one queue per
queryKey. - Applies the request mode: concurrent, deduplicated, cancelable or queued.
- Controls queues: pause, stop, start, flush and persist them.
// Hold every request of one queue, then let them go
client.fetchDispatcher.stop(getUser.queryKey);
getUser.send();
client.fetchDispatcher.start(getUser.queryKey); // the held request is sent now
exec() skips the dispatcher. Only send() gets the features on this page.
Choose a mode per queue
The mode comes from the request options. When a request joins a queue, the first matching rule wins.
| Order | Option | Mode | What happens |
|---|---|---|---|
| 1 | queued: true | One by one | Waits until the previous request in the queue finishes |
| 2 | cancelable: true | Cancelable | Aborts the running requests of the queue, then starts |
| 3 | deduplicate: true | Deduplicated | Joins the identical request still in flight and shares its response |
| 4 | none of them | Concurrent | Starts at once, next to the others |
Deduplication is on by default for GET and QUERY with the fetch adapter. It only joins requests in flight, it is not a
cache. Limit the window with deduplicateTime.
A cancelable search needs one shared queryKey, because the default key changes with the query params:
getUsers.setCancelable(true).setQueryKey("users-search"). Guides: deduplication,
cancellation and queueing.
Pause, stop and start a queue
| Method | Running request | Waiting requests |
|---|---|---|
pause(queryKey) | Finishes | Stay in the queue, not started |
stop(queryKey) | Canceled, kept in queue | Stay in the queue, not started |
start(queryKey) | - | Sent in the queue's mode |
A single request cannot be paused. Stop and resume it by id with stopRequest(queryKey, requestId) and
startRequest(queryKey, requestId). Read the id from the onBeforeSent callback of send().
flushQueue(queryKey) sends the pending requests of a queue right away, and flush() does it for every queue. Stopped
queues are skipped.
Retry failed requests
retry sets how many more attempts a failed request gets, retryTime the delay between them (500 ms by default, or a
function such as exponentialBackoff()). send() resolves after the last attempt.
const getReport = client.createRequest()({
endpoint: "/reports",
retry: 3,
retryTime: 1000,
});
Each scheduled retry calls onRetry with its number and delay. See the retries guide.
Wait out offline periods
With offline: true, the default, a request is not sent while the app is offline, and one that fails because the
connection dropped stays in its queue. Both go out when the connection returns. Its send() promise waits until then. Set offline: false to fail at once.
Online state comes from the AppManager. See the offline guide.
Persist queues across reloads
Give a dispatcher an async lazyStorage to keep its queues, for example offline writes, through a reload. On start it
reads the stored requests, puts them in front of the ones added meanwhile and sends them.
import { createClient, Dispatcher } from "@hyper-fetch/core";
import { del, get, keys, set } from "idb-keyval";
export const client = createClient({
url: "https://api.example.com",
submitDispatcher: () =>
new Dispatcher({
lazyStorage: {
get: (key) => get(key),
set: (key, value) => set(key, value),
keys: () => keys() as Promise<string[]>,
delete: (key) => del(key),
},
}),
});
Requests are stored with toJSON(), so functions on them (mappers, a function retryTime) are not kept.
Watch the queues
Each dispatcher has an events object with onQueueChange, onQueueStatusChange, onDrained and
onRunningRequestsChange, each with a ...ByKey variant for one queue. They return an unsubscribe function.
const unsubscribe = client.fetchDispatcher.events.onRunningRequestsChange(
({ queryKey, runningRequests }) => {
console.log(`${queryKey}: ${runningRequests.length} running`);
},
);
Plugins get the same changes through onDispatcherItemAdded, onDispatcherQueueDrained and the
other dispatcher hooks. In React, useQueue and
useIsFetching build on these events.
Methods
| Name | Description |
|---|---|
| Stop particular request |
| Stop request queue and cancel all started requests - those will be treated like not started |
| Start particular request |
| Start request handling by queryKey |
| Set new queue storage value |
| Request can run for some time, once it's done, we have to check if it's successful or if it was aborted It can be different once the previous call was set as cancelled and removed from queue before this request got resolved |
| Pause request queue, but do not cancel already started requests |
| |
| Add request count to the queryKey |
| Get the value based on the currently running requests |
| Check if request is currently processing |
| Get currently running requests |
| Get running request by id |
| Return request from queue state |
| Return all queue keys currently tracked by the dispatcher storage |
| Get count of requests from the same queryKey |
| Return queue state object.
Automatically reconstructs any serialized (JSON) requests back into
proper Request class instances so the rest of the pipeline can rely on
having a real
RequestInstance
. |
| Get value of the active queue status based on the stopped status |
| Get currently running requests from all queryKeys |
| Method used to flush the queue requests |
| Flush all available requests from all queues |
| Delete all started requests, but do NOT clear it from queue and do NOT cancel them |
| Delete request by id, but do NOT clear it from queue and do NOT cancel them |
| Delete from the storage and cancel request |
| Create storage element from request |
| Clear requests from queue cache |
| Clear all running requests and storage |
| Cancel all started requests, but do NOT remove it from main storage |
| Cancel started request, but do NOT remove it from main storage |
| Add request to the running requests list |
| Add new element to storage |
| Add request to the dispatcher handler |
send()adds requests to a queue perqueryKeyinfetchDispatcher(GET, QUERY) orsubmitDispatcher.- The mode is
queued, thencancelable, thendeduplicate, else concurrent. - Queues can be paused, stopped, started, flushed and persisted with
lazyStorage.
Next steps
Runnable examples: Deduplication, Queue, Offline queue and Resume after reload.