Skip to content

reactive/data-client / .agents/skills/data-client-manager

data-client-manager

Verified

Write @data-client Managers, the runtime layer that bridges the store to the world outside the view framework: global side effects and real-time data such as websockets, SSE and polling. A Manager reacts to every request or to events from outside the app, and moves data into or out of the store. Use one instead of useEffect for behavior that belongs to the whole app, such as error toasts and reporting, logging and analytics, auth failures, refetching on focus or reconnect, and cross-tab sync. Not for the shape of data: data built from responses (joined, derived, or accumulated) is defined in a schema, so use data-client-schema.

references/Manager.md

View on GitHub
<!-- Generated by `yarn build:skills` from docs/core/api/Manager.md (react). Edit the source doc, not this file. -->

# Manager

`Managers` handle global side effects. They are like [useEffect()](https://react.dev/reference/react/useEffect), but for the central data
store.

The default managers run the asynchronous behavior that Data Client provides,
such as fetching and subscriptions. Configure them with [getDefaultManagers()](./getDefaultManagers.md), and add your
own `Managers`.

Each Manager implements [middleware](#middleware), which connects it to the store's [control flow](#control-flow).
[init()](#init) and [cleanup()](#cleanup) connect it to the store's lifecycle, for setup and teardown.

```typescript
type Dispatch = (action: ActionTypes) => Promise<void>;

type Middleware = (controller: Controller) => (next: Dispatch) => Dispatch;

interface Manager {
  middleware: Middleware;
  cleanup(): void;
  init?: (state: State<any>) => void;
}
```

## Lifetimes

Each store gets its own Managers. A Manager's code lives at one of three lifetimes:

| Lifetime | Lasts                                                       | Holds                                                      |
| -------- | ----------------------------------------------------------- | ---------------------------------------------------------- |
| Config   | the page                                                    | options passed to the constructor, like a URL or callbacks |
| Store    | one store, from the [managers](#adding) function to unmount | instance fields about the store, like fetches in flight    |
| Active   | [init()](#init) to [cleanup()](#cleanup)                    | timers, connections and listeners                          |

So a constructor only stores its options. React can construct Managers for a store it then discards, so a
constructor must not open anything.

## Lifecycle

### middleware

`middleware` works like a [redux middleware](https://redux.js.org/advanced/middleware), except that `next()` returns a
`Promise`.

With \<DataProvider />, this promise resolves when React
[commits](https://indepth.dev/inside-fiber-in-depth-overview-of-the-new-reconciliation-algorithm-in-react/#general-algorithm)
the update. React schedules commits asynchronously, so a Manager can await `next()` to work with the new state after the
DOM updates.

Redux dispatches synchronously, so a redux store needs an adapter after the Managers that returns a `Promise` from
`next()`. [prepareStore](https://dataclient.io/docs/guides/redux) adds one, and places redux middleware after it.

Middleware can [read actions](#reading-and-consuming-actions) as they are dispatched, and
[dispatch its own](#dispatching-actions).

### init(state) {#init}

Called when Managers start or resume. Start timers and connections here.

### cleanup()

Called when Managers pause or stop. Stop timers and connections here.

[DataProvider](https://dataclient.io/docs/api/DataProvider) calls `init()` and `cleanup()` from an Effect, so they follow the
[Effect lifecycle](https://react.dev/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development).
React StrictMode, and [`<Activity>`](https://react.dev/reference/react/Activity) hiding `DataProvider`, pause Managers
with `cleanup()` and resume them with `init()` on the same store.

While Managers are paused, the store keeps applying actions. Fetches in flight still resolve, and `middleware` still sees
them. So:

- Don't reset state about the store in `cleanup()`, like fetches in flight.
- Guard side effects that `cleanup()` stopped, like `this.channel?.postMessage()`.

`init()` gets the store's current state, including on resume.

## Adding managers to Reactive Data Client {#adding}

Pass a function to the [managers](https://dataclient.io/docs/api/DataProvider#managers) prop of [DataProvider](https://dataclient.io/docs/api/DataProvider). It
runs once for each store, so a remounted `DataProvider` gets new Managers.

**Web**

```tsx title="index.tsx"
import { DataProvider, getDefaultManagers } from '@data-client/react';
import { createRoot } from 'react-dom/client';
import App from './App';
import MyManager from './MyManager';

const managers = () => [new MyManager(), ...getDefaultManagers()];

createRoot(document.body).render(
  <DataProvider managers={managers}>
    <App />
  </DataProvider>,
);
```

**React Native**

```tsx title="index.tsx"
import { DataProvider, getDefaultManagers } from '@data-client/react';
import { AppRegistry } from 'react-native';
import App from './App';
import MyManager from './MyManager';

const managers = () => [new MyManager(), ...getDefaultManagers()];

const Root = () => (
  <DataProvider managers={managers}>
    <App />
  </DataProvider>
);
AppRegistry.registerComponent('MyApp', () => Root);
```

**NextJS**

```tsx title="app/Provider.tsx"
'use client';
import { getDefaultManagers } from '@data-client/react';
import { DataProvider } from '@data-client/react/nextjs';
import MyManager from './MyManager';

const managers = () => [new MyManager(), ...getDefaultManagers()];

export default function Provider({
  children,
}: {
  children: React.ReactNode;
}) {
  return <DataProvider managers={managers}>{children}</DataProvider>;
}
```

```tsx title="app/layout.tsx"
import Provider from './Provider';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <Provider>{children}</Provider>
      </body>
    </html>
  );
}
```

**Expo**

```tsx title="app/_layout.tsx"
import { Stack } from 'expo-router';
import { DataProvider, getDefaultManagers } from '@data-client/react';
import MyManager from './MyManager';

const managers = () => [new MyManager(), ...getDefaultManagers()];

export default function RootLayout() {
  return (
    <DataProvider managers={managers}>
      <Stack>
        <Stack.Screen name="index" />
      </Stack>
    </DataProvider>
  );
}
```

Define the function at module level: it holds only config.

Actions pass through managers in array order. List custom managers before the defaults: [NetworkManager](https://dataclient.io/docs/api/NetworkManager)
resolves most FETCH actions itself instead of passing them on.

## Control flow

Managers connect to the DataProvider store through their lifecycle methods and
middleware. They read and dispatch [actions](./Actions.md), and read the store's state.

The job of `middleware` is to dispatch actions, respond to [actions](./Actions.md), or both.

### Dispatching Actions

[Controller](./Controller.md) provides type-safe action dispatchers.

```ts title="CurrentTime"
import { Entity } from '@data-client/rest';

export default class CurrentTime extends Entity {
  id = 0;
  time = 0;
}
```

```ts title="TimeManager"
import type { Controller, Manager, Middleware } from '@data-client/react';
import CurrentTime from './CurrentTime';

export default class TimeManager implements Manager {
  declare protected controller: Controller;
  declare protected intervalID?: ReturnType<typeof setInterval>;

  middleware: Middleware = controller => {
    this.controller = controller;
    return next => async action => next(action);
  };

  init() {
    this.intervalID = setInterval(() => {
      this.controller.set(
        CurrentTime,
        { id: 1 },
        { id: 1, time: Date.now() },
      );
    }, 1000);
  }

  cleanup() {
    clearInterval(this.intervalID);
  }
}
```

### Reading and Consuming Actions

`actionTypes` includes all constants to distinguish between different [actions](./Actions.md).

```ts
import type { Manager, Middleware } from '@data-client/react';
import { actionTypes } from '@data-client/react';

export default class LoggingManager implements Manager {
  middleware: Middleware = controller => next => async action => {
    switch (action.type) {
      case actionTypes.SET_RESPONSE:
        if (action.endpoint.sideEffect) {
          console.info(
            `${action.endpoint.name} ${JSON.stringify(action.response)}`,
          );
          // wait for state update to be committed
          await next(action);
          // get the data from the store, which may be merged with existing state
          const { data } = controller.getResponse(
            action.endpoint,
            ...action.args,
            controller.getState(),
          );
          console.info(`${action.endpoint.name} ${JSON.stringify(data)}`);
          return;
        }
      // actions must be explicitly passed to next middleware
      default:
        return next(action);
    }
  };

  cleanup() {}
}
```

Inside each `case`, TypeScript [narrows](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#working-with-union-types)
the action's type, so you can access its members safely.

To consume an [action](./Actions.md), don't call `next()`.

```ts title="isEntity"
import type { Schema, EntityInterface } from '@data-client/react';

export default function isEntity(
  schema: Schema,
): schema is EntityInterface {
  return schema !== null && (schema as any).pk !== undefined;
}
```

```ts title="SubsManager"
import type {
  Manager,
  Middleware,
  EntityInterface,
} from '@data-client/react';
import { actionTypes } from '@data-client/react';
import isEntity from './isEntity';

export default class CustomSubsManager implements Manager {
  declare protected entities: Record<string, EntityInterface>;

  middleware: Middleware = controller => next => async action => {
    switch (action.type) {
      case actionTypes.SUBSCRIBE:
      case actionTypes.UNSUBSCRIBE:
        const { schema } = action.endpoint;
        // only process registered entities
        if (schema && isEntity(schema) && schema.key in this.entities) {
          if (action.type === actionTypes.SUBSCRIBE) {
            this.subscribe(schema.key, action.args[0]?.product_id);
          } else {
            this.unsubscribe(schema.key, action.args[0]?.product_id);
          }

          // consume subscription if we use it
          return Promise.resolve();
        }
      default:
        return next(action);
    }
  };

  cleanup() {}

  subscribe(channel: string, product_id: string) {}
  unsubscribe(channel: string, product_id: string) {}
}
```

`return Promise.resolve();` instead of `next(action)` stops managers listed after this one from seeing the
[action](./Actions.md).

Types: [`FETCH`](./Actions.md#fetch), [`SET`](./Actions.md#set), [`SET_RESPONSE`](./Actions.md#set_response),
[`RESET`](./Actions.md#reset), [`SUBSCRIBE`](./Actions.md#subscribe), [`UNSUBSCRIBE`](./Actions.md#unsubscribe),
[`INVALIDATE`](./Actions.md#invalidate), [`INVALIDATEALL`](./Actions.md#invalidateall), [`EXPIREALL`](./Actions.md#expireall)

## Use cases

Minimal examples for common Manager use cases:

- [Logging](./managers.md#middleware-logging)
- [Error reporting (monitoring)](./managers.md#error-reporting)
- [Metrics (fetch timing)](./managers.md#metrics)
- [Notifications (toasts)](./managers.md#notifications)
- [Refresh on focus or reconnect](./managers.md#refresh-on-focus)
- [Cross-tab synchronization](./managers.md#cross-tab-sync)
- [Offline persistence](./managers.md#persistence)
- [Data streams (websockets/SSE)](./managers.md#data-stream)
- [Authentication: logout on 401](./LogoutManager.md)
- [Periodic updates (interval/ticker)](#dispatching-actions)
- [Custom transport subscriptions](#reading-and-consuming-actions)
deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
Agent Cost Reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
Agent Cost Reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall