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/managers.md

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

# Managers and Middleware

Reactive Data Client uses the [flux store](https://facebookarchive.github.io/flux/docs/in-depth-overview/) pattern, which is
characterized by an easy to [understand and debug](https://dataclient.io/docs/getting-started/debugging) the store's [undirectional data flow](https://en.wikipedia.org/wiki/Unidirectional_Data_Flow_\(computer_science\)). State updates are performed by a [reducer function](https://github.com/reactive/data-client/blob/master/packages/core/src/state/reducer/createReducer.ts#L19).

In flux architectures, it is critical all functions in the flux loop are [pure](https://react.dev/learn/keeping-components-pure).
Managers provide centralized orchestration of side effects. In other words, they are the means to interface
with the world outside Data Client.

For instance, [NetworkManager](https://dataclient.io/docs/api/NetworkManager) orchestrates data fetching and [SubscriptionManager](https://dataclient.io/docs/api/SubscriptionManager)
keeps track of which resources are subscribed with [useLive](https://dataclient.io/docs/api/useLive) or [useSubscription](https://dataclient.io/docs/api/useSubscription). By centralizing control, [NetworkManager](https://dataclient.io/docs/api/NetworkManager) automatically deduplicates fetches, and [SubscriptionManager](https://dataclient.io/docs/api/SubscriptionManager)
will keep only actively rendered resources updated.

This makes [Managers](./Manager.md) the best way to integrate additional side-effects like
[logging](#middleware-logging), [error reporting](#error-reporting), [metrics](#metrics),
[notifications](#notifications), [data streams](#data-stream), [refreshing on focus or reconnect](#refresh-on-focus),
[cross-tab synchronization](#cross-tab-sync), and [offline persistence](#persistence).
They can also be customized to change core behaviors.

| Default managers                                                          |                                                                                                           |
| ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| [NetworkManager](https://dataclient.io/docs/api/NetworkManager)           | Turns fetch dispatches into network calls                                                                 |
| [SubscriptionManager](https://dataclient.io/docs/api/SubscriptionManager) | Handles polling [subscriptions](https://dataclient.io/docs/getting-started/data-dependency#subscriptions) |
| [DevToolsManager](https://dataclient.io/docs/api/DevToolsManager)         | Enables [debugging](https://dataclient.io/docs/getting-started/debugging)                                 |
| Extra managers                                                            |                                                                                                           |
| [LogoutManager](./LogoutManager.md)                                       | Handles HTTP `401` (or other logout conditions)                                                           |

Each store gets its own Managers from the [managers function](./Manager.md#adding). A Manager's constructor
stores its options, its fields hold state about its store, and [init()](./Manager.md#init) and
[cleanup()](./Manager.md#cleanup) start and stop its timers and connections. See
[Manager lifetimes](./Manager.md#lifetimes).

## Examples

Reactive Data Client improves type-safety and ergonomics by performing dispatches and store access with
its [Controller](./Controller.md)

### Middleware logging

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

export default class LoggingManager implements Manager {
  middleware: Middleware = controller => next => async action => {
    console.log('before', action, controller.getState());
    await next(action);
    console.log('after', action, controller.getState());
  };

  cleanup() {}
}
```

### Error reporting {#error-reporting}

| Unawaited fetch fails                                                                | Reaches global handlers (Sentry, console)?   |
| ------------------------------------------------------------------------------------ | -------------------------------------------- |
| Read: hooks, [fetch()](./Controller.md#fetch) without `sideEffect`, `fetchIfStale()` | No: stored, so components reading it show it |
| Mutation: `fetch()` with `sideEffect: true`                                          | Yes                                          |

To report every failed fetch, awaited or not, send [SET\_RESPONSE](./Actions.md#set_response) actions with `error`
set to a service like [Sentry](https://sentry.io):

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

export default class ErrorReportManager implements Manager {
  middleware: Middleware = controller => next => async action => {
    if (action.type === actionTypes.SET_RESPONSE && action.error)
      captureException(action.response, {
        extra: { endpoint: action.endpoint.name, args: action.args },
      });
    return next(action);
  };

  cleanup() {}
}
```

Then [add it](./Manager.md#adding) before the defaults:
`managers = () => [new ErrorReportManager(), ...getDefaultManagers()]`.

### Metrics {#metrics}

Track fetch timing by observing [FETCH](./Actions.md#fetch) actions. `action.meta.promise`
resolves when the fetch completes. List it before `...getDefaultManagers()` so it sees each FETCH
before [NetworkManager](https://dataclient.io/docs/api/NetworkManager) handles it.

```typescript
import {
  type Manager,
  type Middleware,
  actionTypes,
} from '@data-client/react';
import { trackTiming } from './analytics';

export default class MetricsManager implements Manager {
  middleware: Middleware = controller => next => async action => {
    if (action.type === actionTypes.FETCH) {
      const start = performance.now();
      action.meta.promise
        .finally(() => {
          trackTiming(action.endpoint.name, performance.now() - start);
        })
        // the fetch's caller handles errors; this only observes timing
        .catch(() => {});
    }
    return next(action);
  };

  cleanup() {}
}
```

### Notifications (toasts) {#notifications}

Show a toast when any [mutation](https://dataclient.io/rest/guides/side-effects) succeeds or fails.

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

export class Todo extends Entity {
  id = 0;
  title = '';
  completed = false;

  static key = 'Todo';
}
export const TodoResource = resource({
  path: '/todos/:id',
  schema: Todo,
  optimistic: true,
});
```

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

// toast is the app's toast library, e.g. import { toast } from 'sonner'
export default class ToastManager implements Manager {
  middleware: Middleware = controller => next => async action => {
    if (
      action.type === actionTypes.SET_RESPONSE &&
      action.endpoint.sideEffect
    ) {
      if (action.error) toast.error(`${action.endpoint.name} failed`);
      else toast.success(`${action.endpoint.name} succeeded`);
    }
    return next(action);
  };

  cleanup() {}
}
```

```ts title="getManagers"
import { getDefaultManagers } from '@data-client/react';
import ToastManager from './ToastManager';

// the app's managers (DataProvider or DataClientPlugin)
export default function getManagers() {
  return [new ToastManager(), ...getDefaultManagers()];
}
```

### Refresh on focus or reconnect {#refresh-on-focus}

[Controller.expireAll()](./Controller.md#expireAll) marks data as [Stale](https://dataclient.io/docs/concepts/expiry-policy#stale),
triggering refetch of any _actively rendered_ data without suspending ([stale-while-revalidate](https://dataclient.io/docs/concepts/expiry-policy)).
[init()](./Manager.md#init) and [cleanup()](./Manager.md#cleanup) manage the event listeners.

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

export class Rate extends Entity {
  currency = '';
  usd = 0;
  fetchedAt = '';

  pk() {
    return this.currency;
  }
  static key = 'Rate';
}
export const getRate = new RestEndpoint({
  path: '/rates/:currency',
  schema: Rate,
});
```

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

export default class RefreshManager implements Manager {
  declare protected controller: Controller;
  protected handle = () =>
    this.controller.expireAll({ testKey: () => true });

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

  init() {
    window.addEventListener('focus', this.handle);
    window.addEventListener('online', this.handle);
  }

  cleanup() {
    window.removeEventListener('focus', this.handle);
    window.removeEventListener('online', this.handle);
  }
}
```

```ts title="getManagers"
import { getDefaultManagers } from '@data-client/react';
import RefreshManager from './RefreshManager';

// the app's managers (DataProvider or DataClientPlugin)
export default function getManagers() {
  return [new RefreshManager(), ...getDefaultManagers()];
}
```

### Cross-tab synchronization {#cross-tab-sync}

When a mutation succeeds in one tab, mark data stale in all other tabs using
[BroadcastChannel](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel).

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

export default class TabSyncManager implements Manager {
  declare protected controller: Controller;
  declare protected channel?: BroadcastChannel;

  middleware: Middleware = controller => {
    this.controller = controller;
    return next => async action => {
      if (
        action.type === actionTypes.SET_RESPONSE &&
        action.endpoint.sideEffect &&
        !action.error
      )
        this.channel?.postMessage('mutation');
      return next(action);
    };
  };

  init() {
    this.channel = new BroadcastChannel('data-client');
    this.channel.onmessage = () =>
      this.controller.expireAll({ testKey: () => true });
  }

  cleanup() {
    this.channel?.close();
    delete this.channel;
  }
}
```

### Offline persistence {#persistence}

Persist the store with [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)
(here via [idb-keyval](https://www.npmjs.com/package/idb-keyval)); restore it with
[DataProvider's initialState](https://dataclient.io/docs/api/DataProvider#initialState). IndexedDB writes are
asynchronous and use [structured clone](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)
instead of blocking the main thread with JSON serialization like `localStorage` would.
Debouncing writes keeps rapid action bursts cheap. Consider [expiry times](https://dataclient.io/docs/concepts/expiry-policy)
when restoring.

```typescript
import type { Manager, Middleware } from '@data-client/react';
import { set } from 'idb-keyval';

export default class PersistManager implements Manager {
  declare protected timer?: ReturnType<typeof setTimeout>;

  middleware: Middleware = controller => next => async action => {
    await next(action);
    // debounce: persist at most once per second
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      // in-flight optimistic updates reference functions, so are not persistable
      const state = { ...controller.getState(), optimistic: [] };
      set('data-client', state);
    }, 1000);
  };

  cleanup() {
    clearTimeout(this.timer);
  }
}
```

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

const managers = () => [new PersistManager(), ...getDefaultManagers()];
const initialState = await get('data-client');

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

### Middleware data stream (push-based) {#data-stream}

Adding a manager to process data pushed from the server by [websockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API)
or [Server Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) ensures
we can maintain fresh data when the data updates are independent of user action. For example, a trading app's
price, or a real-time collaborative editor.

```typescript
import type {
  Manager,
  Middleware,
  Controller,
  EntityInterface,
} from '@data-client/react';

export default class StreamManager implements Manager {
  declare protected controller: Controller;
  declare protected evtSource: WebSocket | EventSource;
  declare protected createEventSource: () => WebSocket | EventSource;
  declare protected entities: Record<string, EntityInterface>;

  constructor(
    createEventSource: () => WebSocket | EventSource,
    entities: Record<string, EntityInterface>,
  ) {
    this.createEventSource = createEventSource;
    this.entities = entities;
  }

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

  connect() {
    this.evtSource = this.createEventSource();
    this.evtSource.onmessage = (event: MessageEvent) => {
      try {
        const msg: { type: string; args: [any]; data: any } = JSON.parse(
          event.data,
        );
        if (msg.type in this.entities)
          this.controller.set(
            this.entities[msg.type],
            ...msg.args,
            msg.data,
          );
      } catch (e) {
        console.error('Failed to handle message');
        console.error(e);
      }
    };
  }

  init() {
    this.connect();
  }

  cleanup() {
    this.evtSource?.close();
  }
}
```

[Controller.set()](./Controller.md#set) allows directly updating [Querable Schemas](https://dataclient.io/rest/api/schema#queryable)
directly with `event.data`.

Here a `StreamManager` runs in the preview. A simulated server pushes a price every second or so;
replace `PriceSource` with `new EventSource(url)` or `new WebSocket(url)` to use a real one.
Edit the manager and the preview restarts with your version, keeping the prices it already has.
Open the Store to watch each pushed `set` arrive.

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

export class Ticker extends Entity {
  product_id = '';
  price = 0;

  pk() {
    return this.product_id;
  }
  static key = 'Ticker';
}
```

```ts title="PriceSource"
/** Stands in for an EventSource: pushes JSON messages to `onmessage` */
export class PriceSource {
  onmessage: ((event: { data: string }) => void) | null = null;
  protected prices: Record<string, number> = {
    'BTC-USD': 64000,
    'ETH-USD': 3100,
  };
  protected timer = setInterval(() => {
    for (const product_id in this.prices) {
      this.prices[product_id] *= 1 + (Math.random() - 0.5) / 100;
      this.onmessage?.({
        data: JSON.stringify({
          product_id,
          price: Math.round(this.prices[product_id] * 100) / 100,
        }),
      });
    }
  }, 1200);

  close() {
    clearInterval(this.timer);
  }
}
```

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

export default class StreamManager implements Manager {
  declare protected controller: Controller;
  declare protected source: PriceSource;

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

  init() {
    this.source = new PriceSource();
    this.source.onmessage = event => {
      const ticker = JSON.parse(event.data);
      this.controller.set(
        Ticker,
        { product_id: ticker.product_id },
        ticker,
      );
    };
  }

  cleanup() {
    this.source.close();
  }
}
```

```ts title="getManagers"
import { getDefaultManagers } from '@data-client/react';
import StreamManager from './StreamManager';

// passed to <DataProvider managers={getManagers}>
export default function getManagers() {
  return [new StreamManager(), ...getDefaultManagers()];
}
```

#### Batching high-frequency updates {#batching}

Streams like exchange tickers can send hundreds of messages per second, and connections often start with a large snapshot.
Rather than calling `set()` per message, buffer them and write each batch with an [Array](https://dataclient.io/rest/api/Array) schema.
[Controller.set(\[Entity\], rows)](./Controller.md#set-array) normalizes every row in one store update.

```typescript
export default class StreamManager implements Manager {
  // ...
  protected buffer: Record<string, any[]> = {};
  declare protected flushTimeout?: ReturnType<typeof setTimeout>;

  connect() {
    this.evtSource = this.createEventSource();
    this.evtSource.onmessage = event => {
      const msg = JSON.parse(event.data);
      if (msg.type in this.entities) {
        (this.buffer[msg.type] ??= []).push(msg.data);
        this.flushTimeout ??= setTimeout(this.flush, 50);
      }
    };
  }

  flush = () => {
    const buffer = this.buffer;
    this.buffer = {};
    this.flushTimeout = undefined;
    for (const type in buffer) {
      this.controller.set([this.entities[type]], buffer[type]);
    }
  };

  cleanup() {
    this.evtSource?.close();
    clearTimeout(this.flushTimeout);
    this.flushTimeout = undefined;
    this.buffer = {};
  }
}
```

Rows in one batch that share a pk merge in order and skip [Entity.shouldReorder()](https://dataclient.io/rest/api/Entity#shouldreorder),
so buffer only the latest message per pk when order matters.

Try both buttons below. This browser check starts from an empty store and times `Promise.all` of 500 `set()`
calls against one batch `set()`. Both paths are one React commit, and each writes 500 new prices.

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

export class Ticker extends Entity {
  product_id = '';
  price = 0;

  pk() {
    return this.product_id;
  }
  static key = 'Ticker';
}

export const newPrices = () =>
  Array.from({ length: 500 }, (_, i) => ({
    product_id: `COIN-${i}`,
    price: Math.round(Math.random() * 10000) / 100,
  }));
```

```tsx title="Timing"
import React from 'react';
import NumberFlow from '@number-flow/react';

// Times write(), leaving makeInput() out of the measurement
export function useTimed<T>(
  makeInput: () => T,
  write: (input: T) => Promise<unknown>,
) {
  const [ms, setMs] = React.useState<number>();
  const run = async () => {
    const input = makeInput();
    const start = performance.now();
    await write(input);
    setMs(performance.now() - start);
  };
  return [ms, run] as const;
}

export function Timing({
  label,
  ms,
}: {
  label: string;
  ms: number | undefined;
}) {
  return (
    <div>
      <dt>{label}</dt>
      <dd>
        {ms !== undefined && (
          <NumberFlow
            value={ms}
            format={{ maximumFractionDigits: 1 }}
            suffix=" ms"
          />
        )}
      </dd>
    </div>
  );
}
```

```tsx title="PriceHeader"
import { useQuery } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { Ticker } from './Ticker';

export default function PriceHeader() {
  const first = useQuery(Ticker, { product_id: 'COIN-0' });
  return (
    <header className="appHeader">
      <h1 className="appTitle">Prices</h1>
      {first && (
        <span className="meta">
          COIN-0{' '}
          <NumberFlow
            value={first.price}
            format={{ style: 'currency', currency: 'USD' }}
          />
        </span>
      )}
    </header>
  );
}
```

```tsx title="PriceStream" {10,14}
import { useController } from '@data-client/react';
import { Ticker, newPrices } from './Ticker';
import { useTimed, Timing } from './Timing';
import PriceHeader from './PriceHeader';

function PriceStream() {
  const ctrl = useController();
  const [perRowMs, perRow] = useTimed(newPrices, rows =>
    Promise.all(
      rows.map(row => ctrl.set(Ticker, { product_id: row.product_id }, row)),
    ),
  );
  const [batchMs, batch] = useTimed(newPrices, rows =>
    ctrl.set([Ticker], rows),
  );

  return (
    <>
      <PriceHeader />
      <dl className="stats">
        <Timing label="500 set() calls" ms={perRowMs} />
        <Timing label="1 batch set()" ms={batchMs} />
      </dl>
      <div className="buttonGroup">
        <button onClick={perRow}>set() per row</button>
        <button onClick={batch}>batch set()</button>
      </div>
    </>
  );
}
render(<PriceStream />);
```

#### Skipping DevTools for high-frequency updates

When using WebSockets or other real-time data sources, you may want to skip logging
certain high-frequency actions to [DevToolsManager](https://dataclient.io/docs/api/DevToolsManager) to avoid
overwhelming the browser extension.

```typescript
import { getDefaultManagers, actionTypes } from '@data-client/react';
import StreamManager from './StreamManager';
import { Ticker } from './Ticker';

export default function getManagers() {
  return [
    new StreamManager(() => new WebSocket('wss://ws-feed.example.com'), {
      ticker: Ticker,
    }),
    ...getDefaultManagers({
      devToolsManager: {
        // Increase latency buffer for high-frequency updates
        latency: 1000,
        // Skip WebSocket SET actions to avoid log spam
        // (batched writes use the [Ticker] schema)
        predicate: (state, action) =>
          action.type !== actionTypes.SET ||
          (action.schema !== Ticker && action.schema[0] !== Ticker),
      },
    }),
  ];
}
```

### Coin App

Example app: [coin-app](https://github.com/reactive/data-client/tree/master/examples/coin-app) ([`src/getManagers.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/getManagers.ts), [`src/resources/Ticker.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/resources/Ticker.ts), [`src/pages/AssetDetail/AssetPrice.tsx`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/pages/AssetDetail/AssetPrice.tsx), [`src/resources/StreamManager.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/resources/StreamManager.ts))
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