@background-tasks/react
v0.1.1
Published
React bindings for @background-tasks/core.
Downloads
213
Maintainers
Readme
@background-tasks/react
React bindings for @background-tasks/core.
This package is intentionally thin. It provides a provider and hooks for working
with a BackgroundTaskManager, but it does not ship queue UI, dialogs, toasts,
or styling. Applications keep full control over their own interface.
The package is in early development. Public APIs may change before the first stable release.
Install
npm install @background-tasks/core @background-tasks/react@background-tasks/core and react are peer dependencies.
Setup
Create the manager with @background-tasks/core, then pass it to the provider.
import { BackgroundTaskManager, IndexedDbTaskStorage } from '@background-tasks/core';
import { BackgroundTaskProvider } from '@background-tasks/react';
const manager = new BackgroundTaskManager<AppTasks>({
ownerKey: 'user-123',
namespace: 'my-app',
definitions,
storage: new IndexedDbTaskStorage<AppTasks>({
databaseName: 'my-app-background-tasks',
}),
});
export function App() {
return (
<BackgroundTaskProvider manager={manager} autoStart>
<TaskQueue />
</BackgroundTaskProvider>
);
}autoStart starts the manager when the provider mounts. By default,
stopOnUnmount follows autoStart, so an auto-started manager is stopped when
the provider unmounts.
Hooks
useBackgroundTaskManager<TTasks>()
Returns the manager from React context.
const manager = useBackgroundTaskManager<AppTasks>();The hook throws when used outside BackgroundTaskProvider.
useBackgroundTaskSnapshot<TTasks>()
Subscribes to manager events and returns the current snapshot.
const snapshot = useBackgroundTaskSnapshot<AppTasks>();
console.log(snapshot.status);
console.log(snapshot.counts.running);
console.log(snapshot.tasks);Use this when a component needs the manager status, task counts, and task list.
useBackgroundTasks<TTasks>()
Returns only the task list from the current snapshot.
const tasks = useBackgroundTasks<AppTasks>();Use this for simple queue rendering.
useBackgroundTask<TTasks>(id, type?)
Returns a single task by id. Passing type narrows the task type.
const task = useBackgroundTask<AppTasks, AppTaskType.GenerateReport>(
taskId,
AppTaskType.GenerateReport,
);Use this for task detail screens or row-level components.
useBackgroundTaskActions<TTasks>()
Returns stable wrappers around manager actions.
const {
enqueue,
pause,
resume,
cancel,
clearStorage,
start,
stop,
} = useBackgroundTaskActions<AppTasks>();
await enqueue({
type: AppTaskType.GenerateReport,
payload: {
reportId: 'report-42',
},
});Example
The repository includes a React playground under packages/react/example.
npm install
npm run dev:exampleThe example shows typed task definitions, editable manager settings, editable task payloads, polling, retries, pause/resume, cancellation, deduplication, and browser coordination.
Development
npx nx build react
npx nx test react --run
npx nx lint reactLicense
MIT
