API reference

Everything the package exports, with signatures, defaults and behaviour.

Entry pointExports
@nijatk/react-native-queuekit createQueue, memoryStorage, alwaysOnline, netInfoMonitor, flushOnForeground, backoffDelay, DEFAULT_RETRY, parseRetryAfter, Detached, NonRetryableError, RetryAfterError, TimeoutError, and all types
@nijatk/react-native-queuekit/react QueueProvider, useQueue, useJobs, useJob, useQueueStats

Functions

createQueue

Creates a queue. Jobs saved by a previous session are loaded immediately (running jobs are queued to run again, unless detached). Starts processing unless autoStart is false.

OptionTypeDefaultDescription
storageQueueStoragerequiredWhere jobs are saved. An MMKV instance works directly.
namestring"default"Separates queues that share one storage.
handlersHandlers{}Handlers registered up front, by job type. Prefer define().
networkNetworkMonitoralwaysOnlineConnectivity source.
concurrencynumber3Maximum jobs running at once.
timeoutMsnumber30000Per-attempt timeout.
retryPartial<RetryPolicy>see RetryPolicyBackoff settings.
limitsRecord<string, TypeLimit>{}Per-type concurrency and rate limits.
migrationsRecord<string, Migration>{}Payload upgrades, applied once on load.
autoStartbooleantrueStart processing immediately.
strictbooleantrue, except when __DEV__ is trueThrow when a job type is defined again with a different handler, instead of silently replacing it. See duplicate names.
maxPayloadBytesnumber65536Largest payload (UTF-8 bytes of its JSON) enqueue() accepts; larger ones throw. Infinity disables.
retention{ maxFailed?, failedTtlMs? }noneDelete failed jobs automatically (oldest first beyond maxFailed, or failedTtlMs after failing). Emits removed.
leaseboolean | { ttlMs?: number }falseLet only one instance sharing this storage and name run jobs. See Several instances. ttlMs defaults to 15000.

memoryStorage

In-memory storage. Nothing survives a restart. For tests and previews.

netInfoMonitor and alwaysOnline

netInfoMonitor adapts @react-native-community/netinfo (pass its default export). Online unless isConnected or isInternetReachable is false. alwaysOnline is the default monitor.

flushOnForeground

Calls queue.flush() whenever the app state becomes "active". Returns an unsubscribe function.

backoffDelay

The wait after failure number attempt (1-based): min(maxDelayMs, baseDelayMs * 2^(attempt-1)), jittered to 50% to 100% if enabled. random defaults to Math.random; pass your own for deterministic tests.

parseRetryAfter

Parses a Retry-After header (seconds or HTTP date) to milliseconds, never negative. Returns undefined for a missing or unparseable value. now defaults to Date.now().

Queue methods

queue.define

Registers the handler for type (replacing any previous one) and returns a JobFn that enqueues it. The payload type P is inferred from the handler. defaults apply to every call; call-site options win.

queue.handler

Method decorator (standard TC39). Instance methods register on construction, bound to the instance (last instance wins); static methods register once at class definition. Enqueue with queue.enqueue(method, payload).

queue.enqueue

Saves a job and schedules it. The job is in storage before the call returns. If options.id or options.dedupeKey matches an existing job, that job is returned and nothing is added. The second overload takes a method decorated with @queue.handler and throws if it is not decorated.

queue.register

Lower-level handler registration. Jobs of that type that were waiting for a handler become eligible.

queue.start / queue.stop

start begins processing and subscribes to connectivity changes (idempotent). stop stops picking up jobs and unsubscribes; running jobs finish.

queue.retry

Requeues a failed job with attempts reset and any expiresAt cleared. Returns false if the job is unknown or not failed.

queue.remove / queue.clear

remove deletes a job in any state; a running job is aborted through its signal. Returns false if unknown. clear removes every job.

queue.complete / queue.fail

Finish a job that was detached with ctx.detach(). complete deletes it and emits completed. fail retries or fails it as if the handler had thrown error (default "External task failed"). Both return false if the job is unknown or not detached.

queue.flush

Re-reads connectivity and starts everything due now. Does nothing on a stopped queue.

queue.drain

Flushes, then resolves when no job is running and no job that may start (before the timeout) is waiting. Resolves true when idle, false if timeoutMs elapsed first. Offline-blocked, handler-less and detached jobs are not waited for. A stopped queue is idle.

queue.getJobs

Jobs, oldest first. Without a filter, the same array instance is returned until something changes.

queue.getStats

Counts by status. The same object is returned until something changes.

queue.subscribe

Calls listener after any change to any job. Returns an unsubscribe function. Compatible with useSyncExternalStore.

queue.on / queue.observe

on listens to one event. observe receives every event as a QueueEventInfo, including durationMs. Errors thrown by listeners are swallowed. Both return an unsubscribe function.

queue.isLeader

Whether this instance may run jobs. Always true without lease; with it, true only while this instance holds the lease (and false before start()).

queue.dispose

Stops the queue and removes all listeners and observers. Stored jobs are kept.

React (@nijatk/react-native-queuekit/react)

See React hooks. useQueue throws outside a QueueProvider.

Errors and classes

ClassConstructorUse
NonRetryableErrornew NonRetryableError(message)Throw to fail a job immediately.
RetryAfterErrornew RetryAfterError(delayMs, message?)Throw to retry after a specific delay. Exposes delayMs. Default message "Retry after Nms".
TimeoutErrornew TimeoutError(ms)Created by the queue when an attempt exceeds timeoutMs.
Detachednew Detached(externalId)The value ctx.detach() returns. Exposes externalId.

Types

Job

FieldTypeDescription
idstringUnique id. A good idempotency key.
typestringSelects the handler.
payloadPJSON data for the handler.
statusJobStatus"pending" | "active" | "failed"
prioritynumberHigher runs first.
attemptsnumberFailed attempts so far (offline requeues are not counted).
maxAttemptsnumberAttempts before failed.
createdAtnumberEpoch ms.
runAtnumberEarliest start, epoch ms. Moves forward on each retry.
requiresNetworkbooleanWaits for connectivity.
dedupeKey?stringDe-duplication key.
lastError?stringMessage of the latest error.
progress?number0 to 1 for the current attempt.
externalId?stringNative task id while detached.
expiresAt?numberDeadline from ttlMs, epoch ms.
version?numberPayload version from migrations (missing means 1).
orderKey?stringOrdering group from orderKey.
timeoutMs?numberPer-job attempt timeout.
retry?Partial<RetryPolicy>Per-job retry settings.
failedAt?numberWhen the job failed, epoch ms.
sensitive?booleanPayload hidden from listeners.

JobStatus

EnqueueOptions

JobContext

JobHandler

May be sync, async, or a generator. Return or resolve to succeed; throw to retry.

JobFn

HandlerDecorator

Handlers

QueueConfig

The options object of createQueue.

TypeLimit

Migration

RetryPolicy

QueueStats

JobFilter

QueueEvent

QueueEventInfo

DrainOptions

QueueStorage

NetworkMonitor

Queue

The object createQueue returns. Its methods are listed under Queue methods.

Defaults at a glance

SettingDefault
Queue name"default"
Concurrency3
Attempt timeout30 000 ms
Max attempts5
Backoff base / max1 000 ms / 60 000 ms, jitter on
Network monitoralwaysOnline
Auto starttrue
Job priority0
Job requiresNetworktrue
Job delayMs0