Skip to main content
Version: v10.5.0

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.

Purpose
  1. Know the environment: online, offline, focused or blurred.
  2. Observe every request: start, progress, retry, response, abort and removal events.
  3. Log what the client does, filtered by level and module.
api/events.ts
// Every listener returns an unsubscribe function
const unsubscribe = client.requestManager.events.onResponse(
({ request, response }) => {
console.log(request.endpoint, response.status);
},
);

unsubscribe();

AppManager​

Read the API Reference »

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.

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

getAppManagerEvents
Name Type Description
emitBlur
() => void
Emit when the application window loses focus
emitFocus
() => void
Emit when the application window gains focus
emitOffline
() => void
Emit when the application transitions to offline state
emitOnline
() => void
Emit when the application transitions to online state
onBlur
(callback: () => void) => VoidFunction
Listen for blur events
onFocus
(callback: () => void) => VoidFunction
Listen for focus events
onOffline
(callback: () => void) => VoidFunction
Listen for offline state transitions
onOnline
(callback: () => void) => VoidFunction
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.

api/client.ts
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)),
}),
});
OptionDefaultDescription
initiallyFocusedtrueFocus state before the first event
initiallyOnlinenavigator.onLineOnline state before the first event
focusEventwindow focus and blur, visibilitychangeSubscribes to focus changes
onlineEventwindow online eventsSubscribes to network changes

RequestManager​

Read the API Reference »

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).

Progress and retries
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`,
);
});

getRequestManagerEvents
Name Type Description
emitAbort
(data: RequestEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit when a request is aborted
emitDeduplicated
(data: RequestDeduplicatedEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit when a request is deduplicated (skipped because an identical one is in-flight)
emitDownloadProgress
(data: RequestProgressEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit download progress updates
emitLoading
(data: RequestLoadingEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit loading state changes for a request
emitRemove
(data: RequestRemovedEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit when a request is removed from the dispatcher queue
emitRequestStart
(data: RequestEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit when a request starts being sent
emitResponse
<Adapter>(data: RequestResponseEventType<ExtendRequest<RequestInstance, { client: Client<any, Adapter> }>>, isTriggeredExternally: boolean) => void
Emit when a response is received
emitResponseStart
(data: RequestEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit when the response starts being received
emitRetry
(data: RequestRetryEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit when a failed attempt schedules a retry - after its response, before the wait for the next attempt
emitUploadProgress
(data: RequestProgressEventType<RequestInstance>, isTriggeredExternally: boolean) => void
Emit upload progress updates
onAbort
<T>(callback: (request: RequestEventType<T>) => void) => VoidFunction
onAbortById
<T>(requestId: string, callback: (data: RequestEventType<T>) => void) => VoidFunction
onAbortByKey
<T>(abortKey: string, callback: (request: RequestEventType<T>) => void) => VoidFunction
onDeduplicated
<T>(callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction
Listen for deduplicated request events
onDeduplicatedByCache
<T>(cacheKey: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction
onDeduplicatedById
<T>(requestId: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction
onDeduplicatedByQueue
<T>(queryKey: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction
onDownloadProgress
<T>(callback: (data: RequestProgressEventType<T>) => void) => VoidFunction
onDownloadProgressById
<T>(requestId: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction
onDownloadProgressByQueue
<T>(queryKey: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction
onLoading
<T>(callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction
onLoadingByCache
<T>(cacheKey: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction
onLoadingById
<T>(requestId: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction
onLoadingByQueue
<T>(queryKey: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction
onRemove
<T>(callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction
onRemoveById
<T>(requestId: string, callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction
onRemoveByQueue
<T>(queryKey: string, callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction
onRequestStart
<T>(callback: (details: RequestEventType<T>) => void) => VoidFunction
onRequestStartById
<T>(requestId: string, callback: (details: RequestEventType<T>) => void) => VoidFunction
onRequestStartByQueue
<T>(queryKey: string, callback: (details: RequestEventType<T>) => void) => VoidFunction
onResponse
<T>(callback: (data: RequestResponseEventType<T>) => void) => VoidFunction
onResponseByCache
<T>(cacheKey: string, callback: (data: RequestResponseEventType<T>) => void) => VoidFunction
onResponseById
<T>(requestId: string, callback: (data: RequestResponseEventType<T>) => void) => VoidFunction
onResponseStart
<T>(callback: (details: RequestEventType<T>) => void) => VoidFunction
onResponseStartById
<T>(requestId: string, callback: (details: RequestEventType<T>) => void) => VoidFunction
onResponseStartByQueue
<T>(queryKey: string, callback: (details: RequestEventType<T>) => void) => VoidFunction
onRetry
<T>(callback: (data: RequestRetryEventType<T>) => void) => VoidFunction
Listen to every scheduled retry - the event carries the failed response, the retry number and its delay
onRetryById
<T>(requestId: string, callback: (data: RequestRetryEventType<T>) => void) => VoidFunction
Listen to the retries scheduled by one request
onRetryByQueue
<T>(queryKey: string, callback: (data: RequestRetryEventType<T>) => void) => VoidFunction
Listen to the retries scheduled by the requests of the queue
onUploadProgress
<T>(callback: (data: RequestProgressEventType<T>) => void) => VoidFunction
onUploadProgressById
<T>(requestId: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction
onUploadProgressByQueue
<T>(queryKey: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction

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.

api/abort.ts
getUser.abort();
client.requestManager.abortByRequestId(getUser.abortKey, requestId);

LoggerManager​

Read the API Reference »

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.

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

api/client.ts
import { LoggerManager } from "@hyper-fetch/core";

client.setLogger(
() =>
new LoggerManager({
logger: ({ level, module, title }) =>
sendToMonitoring(level, module, title),
}),
);

Summary
  • client.appManager knows focus and online state. Pass focusEvent and onlineEvent outside the browser.
  • client.requestManager.events reports every request step. Listeners return an unsubscribe function.
  • client.setDebug(true) turns on the logger, setLogLevel and setModules filter it.

Next steps​

Runnable examples: Refetch on focus, Download progress and Cancellation.

Cancellation
Abort requests one by one, by key or all at once.
Plugin
Observe the cache and dispatchers too.
RequestManager API reference
Every method and event of the RequestManager.