Managers
Managers hold the app-wide state of a client. The AppManager tracks focus and online state, the RequestManager
emits request lifecycle events and aborts requests, and the LoggerManager creates the loggers every module uses.
Each client has one of each: client.appManager, client.requestManager and client.loggerManager.
- Know the environment: online, offline, focused or blurred.
- Observe every request: start, progress, retry, response, abort and removal events.
- Log what the client does, filtered by level and module.
// Every listener returns an unsubscribe function
const unsubscribe = client.requestManager.events.onResponse(
({ request, response }) => {
console.log(request.endpoint, response.status);
},
);
unsubscribe();
AppManager
The AppManager tracks whether the app is focused and online. The dispatcher holds offline requests until it reports the connection is back, and React hooks use it to refetch on focus or reconnect.
client.appManager.isOnline; // boolean
client.appManager.isFocused; // boolean
const unsubscribe = client.appManager.events.onOffline(() =>
showBanner("You are offline"),
);
The events are onFocus, onBlur, onOnline and onOffline. setOnline(boolean) and setFocused(boolean) change the
state by hand, which helps in tests.
| Name | Type | Description |
|---|---|---|
| emitBlur | | Emit when the application window loses focus |
| emitFocus | | Emit when the application window gains focus |
| emitOffline | | Emit when the application transitions to offline state |
| emitOnline | | Emit when the application transitions to online state |
| onBlur | | Listen for blur events |
| onFocus | | Listen for focus events |
| onOffline | | Listen for offline state transitions |
| onOnline | | Listen for online state transitions |
Connect a non-browser environment
In the browser the AppManager listens to window events. In React Native, Electron or Node.js, pass your own sources
with focusEvent and onlineEvent. Each receives a setter and can return a cleanup function.
import { AppManager, createClient } from "@hyper-fetch/core";
import NetInfo from "@react-native-community/netinfo";
import { AppState } from "react-native";
export const client = createClient({
url: "https://api.example.com",
appManager: () =>
new AppManager({
focusEvent: (setFocused) => {
const subscription = AppState.addEventListener("change", (state) =>
setFocused(state === "active"),
);
return () => subscription.remove();
},
onlineEvent: (setOnline) =>
NetInfo.addEventListener((state) => setOnline(!!state.isConnected)),
}),
});
| Option | Default | Description |
|---|---|---|
initiallyFocused | true | Focus state before the first event |
initiallyOnline | navigator.onLine | Online state before the first event |
focusEvent | window focus and blur, visibilitychange | Subscribes to focus changes |
onlineEvent | window online events | Subscribes to network changes |
RequestManager
The RequestManager emits an event for every step of every request and keeps the abort controllers. Most events come in
three forms: for all requests, by key (...ByQueue, ...ByCache or ...ByKey) and by requestId (...ById).
client.requestManager.events.onDownloadProgressById(
requestId,
({ progress, timeLeft }) => {
console.log(`${progress}%, ${timeLeft} ms left`);
},
);
client.requestManager.events.onRetry(({ request, retry, delay, response }) => {
console.log(
`${request.endpoint}: ${response.status}, retry ${retry} in ${delay} ms`,
);
});
| Name | Type | Description |
|---|---|---|
| emitAbort | | Emit when a request is aborted |
| emitDeduplicated | | Emit when a request is deduplicated (skipped because an identical one is in-flight) |
| emitDownloadProgress | | Emit download progress updates |
| emitLoading | | Emit loading state changes for a request |
| emitRemove | | Emit when a request is removed from the dispatcher queue |
| emitRequestStart | | Emit when a request starts being sent |
| emitResponse | | Emit when a response is received |
| emitResponseStart | | Emit when the response starts being received |
| emitRetry | | Emit when a failed attempt schedules a retry - after its response, before the wait for the next attempt |
| emitUploadProgress | | Emit upload progress updates |
| onAbort | | |
| onAbortById | | |
| onAbortByKey | | |
| onDeduplicated | | Listen for deduplicated request events |
| onDeduplicatedByCache | | |
| onDeduplicatedById | | |
| onDeduplicatedByQueue | | |
| onDownloadProgress | | |
| onDownloadProgressById | | |
| onDownloadProgressByQueue | | |
| onLoading | | |
| onLoadingByCache | | |
| onLoadingById | | |
| onLoadingByQueue | | |
| onRemove | | |
| onRemoveById | | |
| onRemoveByQueue | | |
| onRequestStart | | |
| onRequestStartById | | |
| onRequestStartByQueue | | |
| onResponse | | |
| onResponseByCache | | |
| onResponseById | | |
| onResponseStart | | |
| onResponseStartById | | |
| onResponseStartByQueue | | |
| onRetry | | Listen to every scheduled retry - the event carries the failed response, the retry number and its delay |
| onRetryById | | Listen to the retries scheduled by one request |
| onRetryByQueue | | Listen to the retries scheduled by the requests of the queue |
| onUploadProgress | | |
| onUploadProgressById | | |
| onUploadProgressByQueue | |
Abort requests
request.abort() aborts every request with the same abortKey.
client.requestManager.abortAll() aborts everything in flight, for example on logout or in test teardown. Aborted
requests resolve with an abort error, they do not reject.
getUser.abort();
client.requestManager.abortByRequestId(getUser.abortKey, requestId);
LoggerManager
The LoggerManager prints what the client and its modules do. Nothing is printed until you call setDebug(true). The
level is "warning" by default, change it with setLogLevel.
// "debug" | "info" | "warning" | "error"
client.setDebug(true).setLogLevel("debug");
// Only logs of these modules
client.loggerManager.setModules(["Cache", "Dispatcher"]);
Send the logs somewhere else with setLogger, which takes a function returning a new LoggerManager:
import { LoggerManager } from "@hyper-fetch/core";
client.setLogger(
() =>
new LoggerManager({
logger: ({ level, module, title }) =>
sendToMonitoring(level, module, title),
}),
);
client.appManagerknows focus and online state. PassfocusEventandonlineEventoutside the browser.client.requestManager.eventsreports every request step. Listeners return an unsubscribe function.client.setDebug(true)turns on the logger,setLogLevelandsetModulesfilter it.
Next steps
Runnable examples: Refetch on focus, Download progress and Cancellation.