Skip to main content

Controller

Controller gives type-safe access to the Reactive Data Client store and its lifecycle. Each store has one Controller.

Controller memoizes denormalization for global referential equality: unchanged store data gives the same object wherever it is read. This keeps rendering and lookups fast.

Controller is provided:

class Controller {
/*************** Action Dispatchers ***************/
fetch(endpoint, ...args): ReturnType<E>;
fetchIfStale(endpoint, ...args): Promise<Denormalize<E['schema']>>;
expireAll({ testKey }): Promise<void>;
invalidate(endpoint, ...args): Promise<void>;
invalidateAll({ testKey }): Promise<void>;
resetEntireStore(): Promise<void>;
set(queryable, ...args, value): Promise<void>;
set([Entity], rows): Promise<void>;
setResponse(endpoint, ...args, response): Promise<void>;
setError(endpoint, ...args, error): Promise<void>;
resolve(endpoint, { args, response, fetchedAt, error }): Promise<void>;
subscribe(endpoint, ...args): Promise<void>;
unsubscribe(endpoint, ...args): Promise<void>;
/*************** Data Access ***************/
get(queryable, ...args, state): DenormalizeNullable<typeof queryable> | undefined;
getResponse(endpoint, ...args, state): { data; expiryStatus; expiresAt };
getError(endpoint, ...args, state): ErrorTypes | undefined;
snapshot(state: State<unknown>, fetchedAt?: number): SnapshotInterface;
getState(): State<unknown>;
}

Action Dispatchers​

fetch(endpoint, ...args)​

Fetches the endpoint with the given args. When the fetch completes, the response or error goes into the cache.

import { useController } from '@data-client/react';
import { PostResource } from './PostResource';

function CreatePost() {
const ctrl = useController();

return (
<form
onSubmit={e =>
ctrl.fetch(PostResource.getList.push, new FormData(e.currentTarget))
}
>
{/* ... */}
</form>
);
}
tip

fetch has the same return value as the Endpoint passed to it. With a schema, it returns the denormalized value.

const controller = useController();

const post = await controller.fetch(
PostResource.getList.push,
createPayload,
);
post.title;
post.pk();

Endpoint.sideEffect​

sideEffect changes how fetch() behaves:

true​
  • Resolves before the cache update is committed.
  • Every call starts a new fetch.
  • Unawaited, it rejects unhandled, since no component reads its error. Await it, or use useLoading() to show the error.
false | undefined​
  • Resolves after the cache update is committed.
  • Identical requests are deduplicated, so only one is in flight at a time.
    • To start a new request, abort the one in flight first.
  • Safe unawaited: the error is stored for components reading that endpoint, so it never reaches global unhandled-rejection handlers (report it instead). await still rejects.

fetchIfStale(endpoint, ...args)​

Fetches only when the data is missing, stale or invalid, and always returns a Promise of the latest fetch's outcome. This avoids overfetching fresh data when prefetching.

CacheFetchesawait givesNot awaited
Missing, stale or invalidYes, like fetch()The fetched data, or rejects with its errorThe error is stored; no unhandled rejection
FreshNoThe cached dataNothing happens
The latest fetch failed within errorExpiryLengthNoRejects with that error, like useSuspense() throws itNothing happens

So prefetches don't need to be awaited or caught: components reading that endpoint show a stored error as usual. Unawaited failures don't reach global unhandled-rejection handlers, so report fetch errors with an error reporting Manager. A .then() chained onto the result makes a new Promise, so end that chain with .catch().

// start a secondary request without waiting for it
controller.fetchIfStale(CommentResource.getList, { issueId });
// wait for the data; rejects if that fetch fails
const issue = await controller.fetchIfStale(IssueResource.get, { id: issueId });

To check whether data is cached and fresh without fetching, read getResponse() synchronously.

In route loaders​

A loader starts the next page's fetches before it renders. Like useSuspense(), navigation should wait only when the cached data can't render: when it's missing, invalidated, or stale from an invalidIfStale endpoint. Stale data renders at once and refetches. How to get that depends on what the router waits for:

RouterIn the loaderNothing cached
Changes the route in a transition, like the Next.js App Router, React Router 7, TanStack Router or @anansi/routerStart every fetchIfStale() without awaiting it, so the router has nothing to wait forThe current page stays until the new one is ready, unless the new page has its own Suspense boundary (like an AsyncBoundary or a TanStack Router pendingComponent), which shows its fallback. @anansi/router skips the transition on back and forward
Renders the loader's return value, or doesn't change the route in a transition (React Router 6 without its v7_startTransition flag)Return the cached data when it can render; otherwise return fetchIfStale()The router waits for the fetch

The Next.js App Router has no loaders: useSuspense() fetches as the page renders.

Router with transitions
import type { Controller } from '@data-client/react';
import { CommentResource } from './resources/Comment';
import { IssueResource } from './resources/Issue';

export const issueLoader =
(ctrl: Controller) =>
({ params }: { params: { id: string } }) => {
// not awaited: the route changes at once, and useSuspense() waits inside the transition
ctrl.fetchIfStale(IssueResource.get, { id: params.id });
ctrl.fetchIfStale(CommentResource.getList, { issueId: params.id });
// React Router 6 requires a return value
return null;
};

When server rendering waits for the loader, as @anansi/core's prefetchSpout does for @anansi/router's resolveData, also await the first view's fetch so the first HTML includes its data. Add .catch(() => {}) (or use Promise.allSettled() for several), so a failure never rejects unhandled on the client; useSuspense() still shows the error.

resolveData: async (controller: Controller, { id }: { id: string }) => {
controller.fetchIfStale(CommentResource.getList, { issueId: id });
await controller.fetchIfStale(IssueResource.get, { id }).catch(() => {});
},
Router that renders loader data
import { ExpiryStatus, type Controller } from '@data-client/react';
import { IssueResource } from './resources/Issue';

export const issueLoader =
(ctrl: Controller) =>
({ params }: { params: { id: string } }) => {
const args = { id: params.id };
const { data, expiryStatus } = ctrl.getResponse(
IssueResource.get,
args,
ctrl.getState(),
);
const fetched = ctrl.fetchIfStale(IssueResource.get, args);
// stale data is still Valid, so it returns at once
return expiryStatus === ExpiryStatus.Valid ? data : fetched;
};

A loader that returns a pending fetch lets the router show its own pending and error UI, but it holds navigation while the request runs. That tradeoff comes with waiting for loader data, whatever fetches it.

Explore the github-app example

More Demos

expireAll({ testKey })​

Sets all responses' expiry status matching testKey to Stale.

Use it to refresh only the data on screen when the cache holds many sets of args.

import { type Controller, useController } from '@data-client/react';
import { AccountResource, TradeResource, type Trade } from './resources';
import { Form, FormField } from './Form';

const createTradeHandler =
(ctrl: Controller, userId: string) => async (trade: Trade) => {
await ctrl.fetch(TradeResource.getList.push, { user: userId }, trade);
ctrl.expireAll(AccountResource.get);
ctrl.expireAll(AccountResource.getList);
};

function CreateTrade({ userId }: { userId: string }) {
const handleTrade = createTradeHandler(useController(), userId);

return (
<Form onSubmit={handleTrade}>
<FormField name="ticker" />
<FormField name="amount" type="number" />
<FormField name="price" type="number" />
</Form>
);
}
tip

Often it is better to include mutation side effects in the mutation response. This reduces load, improves performance and keeps state consistent.

invalidate(endpoint, ...args)​

Forces refetching and suspenseon useSuspense with the same Endpoint and parameters.

import { useController, useSuspense } from '@data-client/react';
import { ArticleResource } from './ArticleResource';

function ArticleName({ id }: { id: string }) {
const article = useSuspense(ArticleResource.get, { id });
const ctrl = useController();

return (
<div>
<h1>{article.title}</h1>
<button onClick={() => ctrl.invalidate(ArticleResource.get, { id })}>
Fetch &amp; suspend
</button>
</div>
);
}
tip

To refresh while still showing stale data, use Controller.fetch.

Invalidate many endpoints at once

Use schema.Invalidate to invalidate every endpoint that contains a given entity.

For REST, try Resource.delete.

// deletes MyResource(5)
// this will refetch MyResource.get({id: '5'})
// and remove it from MyResource.getList
controller.setResponse(MyResource.delete, { id: '5' }, { id: '5' });

invalidateAll({ testKey })​

Invalidates all endpoint keys matching testKey.

import { useController, useSuspense } from '@data-client/react';
import { ArticleResource } from './ArticleResource';

function ArticleName({ id }: { id: string }) {
const article = useSuspense(ArticleResource.get, { id });
const ctrl = useController();

return (
<div>
<h1>{article.title}</h1>
<button onClick={() => ctrl.invalidateAll(ArticleResource.get)}>
Fetch &amp; suspend
</button>
</div>
);
}
tip

To refresh while still showing stale data, use Controller.expireAll instead.

The code below invalidates only GET endpoints on the test.com domain. Other domains stay in the cache.

const myDomain = 'http://test.com';
const testKey = (key: string) => key.startsWith(`GET ${myDomain}`);

function useLogout() {
const ctrl = useController();
return () => ctrl.invalidateAll({ testKey });
}

Also clear the cache on 401 (unauthorized) with LogoutManager.

index.tsx
import {
DataProvider,
LogoutManager,
getDefaultManagers,
} from '@data-client/react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { unAuth } from '../authentication';

const myDomain = 'http://test.com';
const testKey = (key: string) => key.startsWith(`GET ${myDomain}`);

const managers = () => [
new LogoutManager({
handleLogout(controller) {
// call custom unAuth function we defined
unAuth();
// still reset the store
controller.invalidateAll({ testKey });
},
}),
...getDefaultManagers(),
];

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

resetEntireStore()​

Clears the entire Reactive Data Client cache. Responses to fetches in flight are not stored. Those fetches reject with a ResetError (error.name === 'ResetError'), except sideEffect fetches, which still settle with their own result or error.

Use it when a user logs out or the authenticated user changes.

import { useController, useSuspense } from '@data-client/react';
import { useCallback } from 'react';
import { CurrentUserResource } from './CurrentUserResource';
import { impersonateUser } from './auth';

const USER_NUMBER_ONE: string = '1111';

function UserName() {
const user = useSuspense(CurrentUserResource.get);
const ctrl = useController();

const becomeAdmin = useCallback(() => {
// Changes the current user
impersonateUser(USER_NUMBER_ONE);
ctrl.resetEntireStore();
}, [ctrl]);
return (
<div>
<h1>{user.name}</h1>
<button onClick={becomeAdmin}>Be Number One</button>
</div>
);
}

set(queryable, ...args, value)​

Updates any Queryable Schema, or many entities at once with an Array or Values schema.

ctrl.set(
Todo,
// which Todo to update
{ id: '5' },
// merge this data into the Todo in the store
{ id: '5', title: 'tell me friends how great Data Client is' },
);

The value is typed by the schema: an Entity takes its fields (numbers and strings may be either), while a Collection or All takes a list of rows. A Query takes the input of the schema it wraps, since set() normalizes that schema rather than reversing process().

ctrl.set(TodoResource.getList.schema, [{ id: '5', completed: true }]);

Collection.push and unshift take the Collection's args, which pick the lists to add to, and one row or a list of rows.

ctrl.set(TodoResource.getList.schema.push, { userId: '1' }, [
{ id: '6', title: 'Buy milk' },
{ id: '7', title: 'Walk dog' },
]);
Unions

When each member declares its discriminator as a literal (like readonly type = 'first'), a Union row is checked against the member it selects, so { type: 'first', secondField: 1 } is an error. Only declared fields are accepted, so a key read by a schemaAttribute function must be declared on each member.

Pass a function to derive the value from the stored one. This prevents race conditions.

const id = '2';
ctrl.set(Article, { id }, article => ({ id, votes: article.votes + 1 }));

set([Entity], rows)​

Pass an Array schema ([Todo] or new schema.Array(Todo)) and a list of rows to update many entities in one store update. Each row merges with its stored entity; entities not in the list are untouched.

ctrl.set(
[Todo],
[
{ id: '5', completed: true },
{ id: '6', completed: false },
],
);

Rows are typed by the Entity's fields; numbers and strings may be either, and object, array and Date values are not checked since rows are raw input.

For lists that mix Entity types, use a Union; each row is stored by its type:

const Feed = new schema.Union({ post: Post, comment: Comment }, 'type');

ctrl.set(
[Feed],
[
{ id: '1', type: 'post', title: 'Hello' },
{ id: '7', type: 'comment', body: 'Nice!' },
],
);

To delete many entities at once, use Invalidate; rows only need their pk fields:

ctrl.set([new schema.Invalidate(Todo)], [{ id: '5' }, { id: '6' }]);

To delete one, pass the Invalidate schema and its row:

ctrl.set(new schema.Invalidate(Todo), { id: '5' });

Values schemas take an object of rows instead:

ctrl.set(new schema.Values(Todo), {
'5': { id: '5', completed: true },
'6': { id: '6', completed: false },
});

Array, Values and Invalidate schemas take no args (so Entity.pk() and Entity.process() receive []) and no updater function. Rows that share a pk merge in list order, without Entity.shouldReorder(). Use this instead of calling set() once per row, such as when batching high-frequency stream updates.

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.

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 />);
Live Preview

setResponse(endpoint, ...args, response)​

Stores response in cache for given Endpoint and args.

Components suspending on this Endpoint and args resolve. Existing data for that Endpoint and args is updated; entities merge with their stored fields.

import { useController } from '@data-client/react';
import { useEffect } from 'react';
import { EndpointLookup } from './EndpointLookup';

function useWebsocketUpdates(url: string) {
const ctrl = useController();

useEffect(() => {
const websocket = new WebSocket(url);

websocket.onmessage = event => {
const { endpoint, args, data } = JSON.parse(event.data);
ctrl.setResponse(EndpointLookup[endpoint], ...args, data);
};

return () => websocket.close();
}, [ctrl, url]);
}

This is a proof of concept in React. A Manager websockets implementation is more robust.

setError(endpoint, ...args, error)​

Stores error as the result of the Endpoint and args.

resolve(endpoint, { args, response, fetchedAt, error })​

Resolves a specific fetch, storing the response in cache.

Like setResponse, but fetchedAt ties the response to one fetch, so that fetch's optimistic update is removed.

NetworkManager uses it. Use it when a Manager processes fetch requests.

Pass the fetch action's action.meta.fetchedAt as fetchedAt. Then the store drops responses to fetches started before resetEntireStore(), and an old response doesn't settle a newer fetch of the same key.

subscribe(endpoint, ...args)​

Adds a subscription to the Endpoint and args. Each call increments its subscriber count.

useSubscription and useLive call this on mount.

Custom hooks can call it to subscribe based on other conditions.

import {
useController,
type EndpointInterface,
type FetchFunction,
type Schema,
} from '@data-client/react';
import { useEffect } from 'react';

function useSubscribe<
E extends EndpointInterface<FetchFunction, Schema | undefined, false | undefined>,
>(endpoint: E, ...args: readonly [...Parameters<E>]) {
const controller = useController();
const key = endpoint.key(...args);

useEffect(() => {
controller.subscribe(endpoint, ...args);
return () => {
controller.unsubscribe(endpoint, ...args);
};
}, [controller, key]);
}

unsubscribe(endpoint, ...args)​

Removes a subscription to the Endpoint and args. Each call decrements its subscriber count; at 0, automatic updates stop.

useSubscription and useLive call this on unmount.

Data Access​

get(schema, ...args, state)​

Looks up any Queryable Schema in state.

Example​

useQuery builds on it, and Managers can use it to read the store safely.

useQuery.ts
import {
useController,
StateContext,
type Queryable,
type SchemaArgs,
type DenormalizeNullable,
} from '@data-client/react';
import { useContext } from 'react';

/** Oversimplified useQuery */
function useQuery<S extends Queryable>(
schema: S,
...args: SchemaArgs<S>
): DenormalizeNullable<S> | undefined {
const state = useContext(StateContext);
const controller = useController();

return controller.get(schema, ...args, state);
}

getResponse(endpoint, ...args, state)​

returns
{
data: DenormalizeNullable<E['schema']>;
expiryStatus: ExpiryStatus;
expiresAt: number;
}

Gets the response for an endpoint and args from the given state.

data​

The denormalized response. Every member keeps the same reference while its data is unchanged.

expiryStatus​

export enum ExpiryStatus {
Invalid = 1,
InvalidIfStale,
Valid,
}
Valid​
  • Will never suspend.
  • Might fetch if data is stale
InvalidIfStale​
  • Will suspend if data is stale.
  • Might fetch if data is stale
Invalid​
  • Will always suspend
  • Will always fetch

expiresAt​

When the data expires, as a timestamp. Compare it to Date.now().

Example​

useCache and useSuspense build on it. Managers can use it to look up a response in the given state.

useCache.ts
import {
useController,
StateContext,
type EndpointInterface,
} from '@data-client/react';
import { useContext } from 'react';

/** Oversimplified useCache */
function useCache<E extends EndpointInterface>(
endpoint: E,
...args: readonly [...Parameters<E>]
) {
const state = useContext(StateContext);
const controller = useController();
return controller.getResponse(endpoint, ...args, state).data;
}
MyManager.ts
import {
type Manager,
type Middleware,
actionTypes,
} from '@data-client/react';

export default class MyManager implements Manager {
declare protected websocket: WebSocket;

middleware: Middleware = controller => {
return next => async action => {
if (action.type === actionTypes.FETCH) {
console.log('The existing response of the requested fetch');
console.log(
controller.getResponse(
action.endpoint,
...action.args,
controller.getState(),
).data,
);
}
next(action);
};
};

cleanup() {
this.websocket.close();
}
}

getError(endpoint, ...args, state)​

Gets the error for an endpoint and args, or undefined if there is none.

snapshot(state, fetchedAt)​

Returns a Snapshot.

getState()​

Gets the internal state of Reactive Data Client that has already been committed.

warning

Use it only outside components: in Managers, or in code like router loaders.

Calling getState() during render can cause data tearing.

To act on a mutation's result, use the value fetch() resolves with instead of getState(). A mutation resolves before the store is updated, so getState() doesn't have its response yet. The resolved value is the denormalized response.

import { useController } from '@data-client/react';
import { useNavigate } from 'react-router';
import { PostResource } from './PostResource';

function UpdatePost({ id }: { id: string }) {
const ctrl = useController();
const navigate = useNavigate();

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const post = await ctrl.fetch(
PostResource.update,
{ id },
new FormData(e.currentTarget),
);
navigate(`/posts/${post.id}`);
};

return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}