Skip to main content
Version: v10.5.0

Dispatcher

Read the API Reference »

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.

Purpose
  1. Runs requests from queues, one queue per queryKey.
  2. Applies the request mode: concurrent, deduplicated, cancelable or queued.
  3. Controls queues: pause, stop, start, flush and persist them.
src/queue.ts
// 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.

OrderOptionModeWhat happens
1queued: trueOne by oneWaits until the previous request in the queue finishes
2cancelable: trueCancelableAborts the running requests of the queue, then starts
3deduplicate: trueDeduplicatedJoins the identical request still in flight and shares its response
4none of themConcurrentStarts 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.

Deduplication
One by one

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​

MethodRunning requestWaiting requests
pause(queryKey)FinishesStay in the queue, not started
stop(queryKey)Canceled, kept in queueStay in the queue, not started
start(queryKey)-Sent in the queue's mode
Stopping request queue

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.

api/reports.ts
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.

Offline handling

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.

api/client.ts
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.

src/queue-monitor.ts
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​

Methods
Name Description
stopRequest(queryKey, requestId)
Stop particular request
stop(queryKey)
Stop request queue and cancel all started requests - those will be treated like not started
startRequest(queryKey, requestId)
Start particular request
start(queryKey)
Start request handling by queryKey
setQueue(queryKey, queue)
Set new queue storage value
performRequest(storageItem)
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(queryKey)
Pause request queue, but do not cancel already started requests
initialize(client)
incrementQueueRequestCount(queryKey)
Add request count to the queryKey
hasRunningRequests(queryKey)
Get the value based on the currently running requests
hasRunningRequest(queryKey, requestId)
Check if request is currently processing
getRunningRequests(queryKey)
Get currently running requests
getRunningRequest(queryKey, requestId)
Get running request by id
getRequest(queryKey, requestId)
Return request from queue state
getQueuesKeys()
Return all queue keys currently tracked by the dispatcher storage
getQueueRequestCount(queryKey)
Get count of requests from the same queryKey
getQueue(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 .
getIsActiveQueue(queryKey)
Get value of the active queue status based on the stopped status
getAllRunningRequests()
Get currently running requests from all queryKeys
flushQueue(queryKey)
Method used to flush the queue requests
flush()
Flush all available requests from all queues
deleteRunningRequests(queryKey)
Delete all started requests, but do NOT clear it from queue and do NOT cancel them
deleteRunningRequest(queryKey, requestId)
Delete request by id, but do NOT clear it from queue and do NOT cancel them
delete(queryKey, requestId, abortKey)
Delete from the storage and cancel request
createStorageItem(request)
Create storage element from request
clearQueue(queryKey)
Clear requests from queue cache
clear()
Clear all running requests and storage
cancelRunningRequests(queryKey)
Cancel all started requests, but do NOT remove it from main storage
cancelRunningRequest(queryKey, requestId)
Cancel started request, but do NOT remove it from main storage
addRunningRequest(queryKey, requestId, request)
Add request to the running requests list
addQueueItem(queryKey, element)
Add new element to storage
add(request)
Add request to the dispatcher handler


Summary
  • send() adds requests to a queue per queryKey in fetchDispatcher (GET, QUERY) or submitDispatcher.
  • The mode is queued, then cancelable, then deduplicate, 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.

Queueing
Send requests one by one and control their queues.
Offline
Keep requests while offline and send them when the connection returns.
Dispatcher API reference
Every method of the Dispatcher class with its signature.