Saltar al contenido principal

v0.19: Batch Controller.set(), Faster TypeScript

· 58 min de lectura
Nathaniel Tucker
Creador de Reactive Data Client

v0.19 lets a Manager write a whole batch of streamed rows in one store update, type-checks endpoint code about 2x faster, and fixes a round of TypeScript and Vue issues.

Batch Controller.set() writes a whole stream of rows, like price tickers from a websocket, in one store update with ctrl.set([Ticker], rows). That is up to 95x faster than one set() per row.

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 />);
Vista previa en vivo
Node setMany into a 500-entity store
50 rows20xOne set() per row 10.8 ms → set([Ticker], rows) 0.54 ms
500 rows95xOne set() per row 103 ms → set([Ticker], rows) 1.08 ms

Faster TypeScript: editors and tsc check RestEndpoint and resource() code about 2x faster with 40% less memory, and still report every error they reported before.

Checking 150 RestEndpoints with long paths
TypeScript 61.9xv0.18 3.83 s → v0.19 1.98 s
TypeScript 72.2xv0.18 1.5 s → v0.19 0.69 s

More in v0.19:

Breaking Changes:

Get ready for future releases:

Adopt new features: npx @data-client/codemods v0.19 src/ --improvements=only batches set() loops and drops workarounds 0.19 makes unnecessary

Performance​

TypeScript runs on every keystroke, the store updates on every streamed message, and your bundle loads on every page view.

Batch Controller.set()​

react vue

A Manager that receives a stream of rows (like price tickers over a websocket) can now write them all with one Controller.set() by passing an Array schema. Before v0.19, [Ticker] was a TypeScript error, so the usual workaround was a set() per row:

Before
ws.onmessage = event => {
const rows = JSON.parse(event.data);
for (const row of rows) {
ctrl.set(Ticker, { product_id: row.product_id }, row);
}
};
After
ws.onmessage = event => {
const rows = JSON.parse(event.data);
ctrl.set([Ticker], rows);
};

Each row merges with its stored entity, and entities not in the list are untouched. Array schemas take no args and no updater function. To batch mixed Entity types, deletes, or rows keyed by id, pass a Union, Invalidate, or Values schema; see Controller.set() for examples. #4103

Performance​

Each set() is a separate store update, and every store update copies that entity type's table. Writing rows one at a time repeats that copy for every row, so the cost grows with both the batch size and the store size. A batch pays that copy once.

The chart at the top of this post is the node setMany benchmark in examples/benchmark/core.js: a store that already holds 500 entities, then a synchronous set() per row against one set([Ticker], rows). It measures the store update: 20x faster for 50 rows and 95x faster for 500 rows. #4103

Benchmarks over time | View setMany benchmark

In a Manager, buffer incoming messages and flush each batch with one set(), as described in Batching high-frequency updates. The coin app's StreamManager now flushes Coinbase ticker messages this way.

StreamManager.ts
handleMessage(msg: any) {
if (msg.type in this.entities) {
(this.buffer[msg.type] ??= {})[msg.product_id] = msg;
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]], Object.values(buffer[type]));
}
};

Explora el ejemplo coin-app

Más demos

consejo

If you filter DevToolsManager actions by schema, a batched write's action.schema is the Array schema, so match action.schema[0] for [Ticker] rather than the Entity itself.

Faster Redux DevTools​

react vue

With the Redux DevTools extension open, every store update in development serializes the whole store for the extension, and each timestamp in it was formatted the slow way. Large stores or frequent updates, like polling, live data or many controller.set() calls, made the page stutter. Each update now serializes 40-60x faster, and timestamps still read like 10:42:07.123 AM (#4163). Production builds don't include DevTools, so they are unaffected.

DevTools serialization per store update
50 entities60xv0.18 18.6 ms → v0.19 0.31 ms
500 entities40xv0.18 201 ms → v0.19 5 ms

Shorter React Native GC pauses​

react

React Native apps no longer freeze for 0.5–3 s at a time while they read a large result that keeps updating, like a few thousand entities joined with live prices (#4594). The longest read, pauses included, is now 10x to 90x faster.

Speedup of the longest read in Hermes, GC pauses included
Long nested list, first read10xBefore 405 ms → After 39 ms
Long and short reads, entity cache only90xBefore 407 ms → After 4.5 ms
50-deep bidirectional chain47xBefore 549 ms → After 11.7 ms
500 one-entity reads18xBefore 243 ms → After 13.8 ms
All() query key57xBefore 200 ms → After 3.5 ms

Each freeze was a garbage collection (GC) pause in Hermes, React Native's JavaScript engine. Data Client's memo cache nested one WeakMap per dependency, and Hermes paused for every level. On React Native, the cache now has one level.

The cache also holds up to 10% less memory. We measured the heap it keeps in Node, so Hermes sizes differ.

Memory the cache holds
Streaming join
3,736 symbols joined to live tickers
-10%
9.68MB → 8.72MB
Large refetch
10,000 rows refetched 20 times
-8%
14.71MB → 13.6MB
Trade tape
100 rows of streaming trades
-4%
2.39MB → 2.3MB

Reads between pauses are up to 2.7x faster too. Small cached reads (the red 0.8x rows) are the exception: they are about 20% slower.

Speedup per read in Hermes, between pauses
500-row screen, after a store change2.7xBefore 4428 µs → After 1646 µs
500-row screen, same store again2.2xBefore 668 µs → After 302 µs
Long nested list, cached1.2xBefore 337 µs → After 274 µs
All() query, cached1.4xBefore 364 µs → After 266 µs
500 one-entity reads, cached0.8xBefore 669 µs → After 805 µs
500 one-entity queries, cached0.8xBefore 1121 µs → After 1328 µs

We measured a release build on an Android emulator, with the median of 5 launches. Web builds don't change.

Benchmark details | View read benchmarks

Faster TypeScript​

rest endpoint graphql

TypeScript re-checks your code on every keystroke in the editor and on every CI build. In apps with many endpoints, heavy library types show up as laggy autocomplete, red squiggles that take seconds to appear, and slower builds. v0.19 makes RestEndpoint, resource() and .extend() much cheaper to check, with no code changes on your side. TypeScript still reports every error it reported before (#4173).

Results​

Our heaviest stress test, a file of 150 RestEndpoints with long paths, .extend() and .paginated(), now checks 2x faster on TypeScript 6 and 2.2x faster on TypeScript 7 (chart at the top of this post), using about 40% less memory. All numbers compare the published v0.18.1 packages with v0.19; check times are the best of 10 runs.

Memory for the same file
TypeScript 61.7xv0.18 365 MB → v0.19 211 MB
TypeScript 71.7xv0.18 220 MB → v0.19 128 MB

Endpoint-heavy code does much less type work. Type instantiations are TypeScript's unit of work: they're deterministic, so they compare cleanly across machines. Union does more work than in v0.18, because v0.19 now type-checks set() values (see below).

Type instantiations by stress test
Long paths2.4xv0.18 822 K → v0.19 341 K
Typical app1.5xv0.18 20.2 K → v0.19 13.4 K
React hooks1.2xv0.18 145 K → v0.19 122 K
Vue1.3xv0.18 62.6 K → v0.19 47.3 K
300 fields1.3xv0.18 17 K → v0.19 12.8 K
Schemas1.2xv0.18 118 K → v0.19 99.3 K
Union0.6xv0.18 9 K → v0.19 16.1 K

Hover or tap a cell for exact numbers.

TS 6 check timeTS 7 check timeTS 6 memory
Long paths
150 RestEndpoints with 6-param paths, .extend() and .paginated()
-48%
3.83s → 1.98s
-54%
1.5s → 0.69s
-42%
365MB → 211MB
Typical app
A few resources with .extend(), .paginated() and hooks
same
0.42s → 0.42s
-15%
0.062s → 0.053s
+3%
106MB → 109MB
React hooks
40 resources through every hook, plus ctrl.fetch() and ctrl.set()
-10%
1.24s → 1.12s
-7%
0.41s → 0.38s
-6%
167MB → 157MB
Vue
The same 40 resources through every composable
same
0.68s → 0.68s
-12%
0.17s → 0.15s
-4%
145MB → 139MB
300 fields
One Entity with 300 fields, read and updated 100 times
-14%
0.44s → 0.38s
-40%
0.086s → 0.052s
-9%
111MB → 101MB
Schemas
All, Query, Invalidate, Array, Object and Collection
-3%
1.1s → 1.07s
-14%
0.36s → 0.31s
-4%
156MB → 150MB
Union
A 30-member Union in a Collection and Values
-2%
0.42s → 0.41s
-4%
0.071s → 0.068s
-6%
107MB → 101MB
set() values
1000 ctrl.set() calls on a 30-member Union, a Collection of it and a 300-field Entity
-28%
1.49s → 1.07s
-54%
0.54s → 0.25s
-26%
176MB → 131MB
set() updaters
1000 ctrl.set(Union, args, prev => ...) updaters on a 30-member Union
-4%
3.58s → 3.43s
+11%
1.67s → 1.85s
+1%
381MB → 384MB

The set() rows measure typed set() values, which v0.18 didn't check at all. Plain values still check faster than before, and updater functions on large Unions check in about the same time even though TypeScript now checks each updater's return value (#4179).

Small files are dominated by TypeScript's fixed startup cost (loading lib.dom.d.ts alone takes about 100MB), so their time and memory barely move. The savings add up as a codebase grows.

What changed​

  • .extend() and .paginated() are shared across all endpoints instead of re-created for each endpoint type.
  • Endpoint options infer as plain object types, so TypeScript stops rebuilding them at every use.
  • Path parameters like /users/:id are read in a single pass.

Before shipping, we turned off every @ts-expect-error in the test suite on TypeScript 4.0 through 7 and confirmed every error still appears in the same place.

On TypeScript 5.x and earlier, a process(value, params) method passed to .extend() also no longer fails with "implicitly has an 'any' type" under strict.

Smaller split bundles​

Apps that split their bundle by page or vendor with webpack, rspack or Turbopack now ship less Data Client code (#4487). Brotli-compressed JavaScript of a two-page app with lazy routes, built from 0.19 without and with this change:

Total JS
rspack 2
tracks webpack
-792 B
77401B → 76609B
Next.js 16 (Turbopack)
-366 B
175072B → 174706B

Vite and single-bundle apps stay about the same size.

These savings let us ship more functionality in 0.19 at about the same size. Against 0.18.2, the same app changes by −171 B with rspack, +257 B with Turbopack and +480 B with Vite.

Every Data Client file was marked sideEffects: false. So bundlers skipped each package's index file and linked every import, like Entity or resource, to the file that defines it. With Data Client split across chunks, webpack then split each package into several groups and wrapped the code they share. Now the entry files of @data-client/rest, endpoint, graphql, core, normalizr and react are marked as having side effects. Bundlers enter each package through its index and merge the package into one module. Code you don't use, like Lazy, is still removed.

Client​

Every app on @data-client/react or @data-client/vue writes to the store with Controller and reads it with hooks or composables. These changes make writes simpler and keep the screen in step with the store.

Delete one entity with set()​

react vue

Passing an Invalidate schema to Controller.set() deletes the entity its row identifies, but the single form was a TypeScript error, so code wrapped it in a one-row batch. It now type-checks, with the row typed by the Entity's fields (#4230):

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

Like batch set(), it takes no args and no updater function.

Fix: Polled lists update from mutations​

react vue

An endpoint given a pollFrequency with .extend() now keeps its schema when it polls. So a polled useLive() list updates right away from mutations and optimistic updates, instead of waiting for the next poll (#4437).

Recent actions on __DC__​

react vue

In development, __DC__.actions lists the store's recent actions, including the fetches made while the page loaded. Coding agents and the browser console can see what the store did without the Redux DevTools extension, and __DC__.controller reads the store with the Controller methods they already know. Stores with the same devtools name now get their own keys, like 'Data Client: My App (2)', instead of the second hiding the first. This replaces __DC_CONTROLLERS__; see the upgrade notes (#4393).

Browser DevTools console
__DC__.actions.slice(-10);

Loading and error states​

The screen should match the data: no endless spinner, no old error after a retry succeeds, no deleted item rendered as present.

Fix: Deleted entities read as undefined​

react vue

When an entity was deleted and its refetch failed, useCache() and useDLE() (React and Vue) returned an internal Symbol as data. A Symbol is truthy, so the usual "not loaded yet" guard let it through and the component rendered as if it had an entity (#4150):

function TodoDetail({ id }: { id: number }) {
const todo = useCache(TodoResource.get, { id });
// a deleted todo used to get past this guard, so todo.title.trim() threw
if (!todo) return <TodoPlaceholder />;
return <h3>{todo.title.trim()}</h3>;
}

Now data is undefined, matching its type and Controller.get(). The same applies to Controller.getResponse(), for example in custom Managers.

If you worked around this, the workaround can go. A plain truthiness check is enough:

Before
function TodoDetail({ id }: { id: number }) {
const todo = useCache(TodoResource.get, { id });
if (!todo || typeof todo === 'symbol') return <TodoPlaceholder />;
return <h3>{todo.title.trim()}</h3>;
}
After
function TodoDetail({ id }: { id: number }) {
const todo = useCache(TodoResource.get, { id });
if (!todo) return <TodoPlaceholder />;
return <h3>{todo.title.trim()}</h3>;
}

To show something specific when the refetch failed (for example a 404 after deletion), read error from useDLE() rather than inspecting data.

Other changes​

  • react Controller.fetch() of an endpoint without sideEffect never rejects unhandled, so a read you don't await needs no .catch(): components reading that endpoint show its stored error. Mutations still reject. This also stops React Native's unhandled rejection warning when a refetch on screen focus fails. Upgrade notes (#4670)
  • react Support React <Activity> above DataProvider. Before, hiding DataProvider dropped responses, fetches and subscriptions, which left useSuspense() loading forever. Most apps should still put DataProvider at the root, above <Activity>, which works as before. A response to a fetch started before resetEntireStore() is always dropped, so custom managers should pass the fetch's own fetchedAt to controller.resolve(); the v0.19 codemod does this where a Manager resolves action.endpoint under an actionTypes.FETCH check (#4593)
  • react vue Fix: useLoading() clears error when the wrapped function is called again, so a form no longer shows an old error after a later submit succeeds. When calls overlap, React and Vue loading and error follow the latest call, and a call that settles inside a hidden <Activity> shows its result once visible (#4614)
  • react vue Fix: A cached result no longer keeps showing a nested entity as missing after that entity was INVALID or null and becomes valid again (#4460)
  • react Fix: useCancelling() no longer aborts the request its own component is waiting on when it re-renders while suspended, which could leave slow requests loading forever (#4516)
  • react Fix: ExternalDataProvider and the Redux DataProvider render updates dispatched from children's mount Effects, like an optimistic controller.fetch(), instead of waiting for the next store change (#4663)

Platforms​

A Data Client upgrade should not hold back your React Native, Babel or image setup.

  • react Support React Native 0.87. It removed InteractionManager, so apps on it crashed as soon as a component called useSuspense(), useFetch() or useDLE(). On 0.87 and later, Data Client waits for idle time with requestIdleCallback(), as React Native recommends (#4355)
  • all Support @babel/runtime 8: apps on Babel 8 share their runtime with Data Client instead of installing a second copy. Apps on Babel 7 keep working (#4209)
  • img Support @data-client/react 0.19 (#4636)
  • react Fix: React Native apps no longer freeze for 0.5–3 s at a time while they read a large result whose entities keep updating. See Shorter React Native GC pauses (#4594)
  • react Fix: React Native useSuspense(), useFetch() and useDLE() refetch on screen focus only when the current data is stale or invalid, instead of refetching fresh data on every refocus (#4378)
  • img Fix: Node's import, and tools that run on it like Vitest, load the ESM build of @data-client/img instead of CommonJS (#4617)

Vue​

Vue composables now handle caching, garbage collection and errors like React hooks, so a pattern you know from React works the same in Vue.

Garbage collection by default​

vue

Vue's DataClientPlugin only removed unused data if you passed a gcPolicy yourself. It now defaults to new GCPolicy(), the same as React's DataProvider, so you can drop the option unless you customize it (#4148).

Before
import { DataClientPlugin, GCPolicy } from '@data-client/vue';

app.use(DataClientPlugin, { gcPolicy: new GCPolicy() });
After
import { DataClientPlugin } from '@data-client/vue';

app.use(DataClientPlugin);

Data is removed only when no mounted component reads it and twice its freshness lifetime has passed since it was fetched (at least two minutes). A sweep checks every five minutes. Anything a component reads again before then is back in use.

A component that mounts after removal treats the data as never fetched: useSuspense() fetches it again, while useCache() returns undefined. To keep unused data longer or sweep less often, pass your own gcPolicy.

Stale-while-revalidate​

vue

When a component mounts with data that is stale but still valid, Vue useSuspense() now renders it right away and refetches in the background, like React. Before, it showed the <Suspense> fallback until the refetch finished (#4169).

Fix: Getter arguments​

vue

Vue composables like useSuspense() and useLive() were typed to accept a getter function as an argument, but they passed the function itself to the endpoint instead of calling it. Getters now work the same as refs and computed, and the composable refetches when anything the getter reads changes (#4115). Drop the computed() wrapper if you only used it to make arguments reactive:

Before
import { computed } from 'vue';

const props = defineProps<{ id: number }>();
const article = await useSuspense(
ArticleResource.get,
computed(() => ({ id: props.id })),
);
After
const props = defineProps<{ id: number }>();
const article = await useSuspense(ArticleResource.get, () => ({
id: props.id,
}));

This applies to every composable that takes endpoint arguments: useSuspense(), useLive(), useCache(), useDLE(), useFetch(), useQuery() and useSubscription().

Other Vue changes​

  • vue Export GCPolicy from @data-client/vue, so a custom gcPolicy no longer needs @data-client/core (#4143)
  • vue Export __INTERNAL__, like @data-client/react, so tooling can use createReducer and initialState without depending on @data-client/core (#4270)
  • vue Fix: useSuspense() and useLive() keep the previous data while new arguments load, instead of returning undefined (#4131)
  • vue Fix: useSuspense() and useLive() send fetch errors after arguments change to onErrorCaptured() instead of an unhandled promise rejection (#4135)
  • vue Fix: useSuspense(), useDLE() and useFetch() no longer refetch stale data on every store update, so a controller.set() is not overwritten (#4134)
  • vue Fix: useDLE() and useCache() keep expired invalidIfStale data through unrelated store updates instead of getting stuck loading (#4142)
  • vue Fix: useFetch() keeps its data from being garbage collected while mounted, like useSuspense(), so a configured gcPolicy no longer evicts prefetched data that components read later (#4152)
  • vue Fix: useFetch() is typed as the read-only Ref it returns, so promise.resolved (always undefined) is now a TypeScript error; read promise.value.resolved instead (#4114)
  • vue Fix: DataClientPlugin installs on Vue versions before 3.5 instead of throwing app.onUnmount is not a function (#4146)

Collection updates​

Lists go wrong at the edges: an item shows twice, lands in the wrong place, or a late response drops an update.

push, unshift, remove, move and getPage now handle every case: one item or a list, a plain or sorted Collection, and responses in any order.

Lists of items​

rest endpoint graphql react vue

Send an array to push or unshift to create every item, or to remove to remove them. The array now goes to the server as JSON instead of "[object Object]", and the deprecated resource().create takes an array too (#4262).

Controller.fetch() typed the result as one item, though it is an array. Reading the array was a TypeScript error, while created.id compiled and was undefined at runtime. The result is now an array, so the cast can go (#4421):

Before
import { useController } from '@data-client/react';
import { TodoResource, type Todo } from './TodoResource';

export function useImportTodos() {
const ctrl = useController();
return async (titles: string[]) => {
const todos = (await ctrl.fetch(
TodoResource.getList.push,
titles.map(title => ({ title })),
)) as unknown as Todo[];
return todos.map(todo => todo.id);
};
}
After
import { useController } from '@data-client/react';
import { TodoResource } from './TodoResource';

export function useImportTodos() {
const ctrl = useController();
return async (titles: string[]) => {
const todos = await ctrl.fetch(
TodoResource.getList.push,
titles.map(title => ({ title })),
);
return todos.map(todo => todo.id);
};
}

A list is typed as an array on any endpoint whose schema is a Collection's push or unshift, like the deprecated resource().create or your own new RestEndpoint() with a Collection.push schema. One item, FormData, or a body typed any is still typed as one item.

Controller.set() with Collection.push or unshift now takes the Collection's args, which pick the lists to add to, and one row or a list of rows. Before, it took the Entity's fields, so the args needed a cast and each row its own call:

Before
function addTodos(ctrl: Controller, userId: string, todos: Todo[]) {
for (const todo of todos) {
ctrl.set(TodoResource.getList.schema.push, { userId } as any, todo);
}
}
After
function addTodos(ctrl: Controller, userId: string, todos: Todo[]) {
ctrl.set(TodoResource.getList.schema.push, { userId }, todos);
}

An updater function (previous => value) is now a TypeScript error there, since an added row has no previous value and the function never ran. Called without args, push adds only to lists with no filter keys, instead of throwing and dropping the write when a filtered list is in the store.

Fix: Sorted and lazy Collections​

rest

Wrapping a Collection in a Query to sort or filter it made push, unshift and remove reject every body except FormData, though they add to the list at runtime. The body is now typed from the Collection's Entity, so the cast can go and a wrong field is a TypeScript error. The same applies to a Collection wrapped in Lazy (#4226).

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

export function useAddPost() {
const ctrl = useController();
return (title: string, author: string) =>
ctrl.fetch(getPosts.push, { group: 'react' }, { title, author } as any);
}
After
import { useController } from '@data-client/react';
import { getPosts } from './getPosts';

export function useAddPost() {
const ctrl = useController();
return (title: string, author: string) =>
ctrl.fetch(getPosts.push, { group: 'react' }, { title, author });
}

where getPosts sorts its Collection with a Query:

getPosts.ts
import { Collection, Entity, Query, RestEndpoint } from '@data-client/rest';

export class Post extends Entity {
id = '';
title = '';
group = '';
author = '';
}

export const getPosts = new RestEndpoint({
path: '/:group/posts',
searchParams: {} as { orderBy?: 'title' | 'author' },
schema: new Query(
new Collection([Post], { nonFilterArgumentKeys: /orderBy/ }),
(posts, { orderBy }: { orderBy?: 'title' | 'author' } = {}) =>
orderBy ?
[...posts].sort((a, b) => a[orderBy].localeCompare(b[orderBy]))
: posts,
),
});

Fix: Re-added items and late responses​

rest endpoint graphql

Collection updates now show each item once, in its place. You do not need to change code.

  • An item that you remove and then add back with push or unshift shows once, not twice (#4487).
  • An update that resolves after a newer refetch of its list still applies to that list (#4566). push adds to the end, remove and move change only their item, and getPage adds below the first page.
  • A create shows its item once when a list fetch starts right after it, in the same millisecond, and already has the item (#4677).

Remove the mug, then undo. The v0.18 replay lists it twice. The live v0.19 cart lists it once:

v0.18

Daily Grind

3 in cart
House blend
2 × $16.00
$32.00
Ceramic mug
1 × $12.00
$12.00
Paper filters
1 × $4.00
$4.00
import { useController, useSuspense } from '@data-client/react';
import { type CartItem, CartResource, usd } from './resources/Cart';

function CartPage() {
  const ctrl = useController();
  const items = useSuspense(CartResource.getList);
  const remove = (item: CartItem) => {
    ctrl.fetch(CartResource.delete, { id: item.id });
    toast.info(`${item.product.name} removed`, {
      label: 'Undo',
      onClick: () => ctrl.fetch(CartResource.getList.push, item),
    });
  };

  return (
    <>
      <header className="appHeader">
        <h1 className="appTitle">Daily Grind</h1>
        <span className="meta">{items.length} in cart</span>
      </header>
      <div className="list">
        <Reorder layoutDependency={items}>
          {items.map(item => (
            <CartRow key={item.id} item={item} onRemove={remove} />
          ))}
        </Reorder>
      </div>
      <Toaster />
    </>
  );
}

function CartRow({ item, onRemove }: Props) {
  return (
    <div className="listItem" ref={useReorderItem(item.id)}>
      <div>
        {item.product.name}
        <div className="meta">
          {item.quantity} × {usd(item.product.price)}
        </div>
      </div>
      <span className="value">{usd(item.total)}</span>
      <CancelButton
        label={`Remove ${item.product.name}`}
        onClick={() => onRemove(item)}
      />
    </div>
  );
}
interface Props {
  item: CartItem;
  onRemove: (item: CartItem) => void;
}
render(<CartPage />);
Vista previa en vivo

Other REST changes​

  • rest Fix: A DELETE endpoint that declares body sends it. Before, the request went out with no body and the last argument became URL params (DELETE /posts?0=5&1=13). If you call such an endpoint without a body, remove body or set body: undefined (#4528)
  • rest Fix: resource()'s delete runs your Endpoint class's process(), or the resource's process option. Before, delete set its own process(), which replaced the base class's, so a base class that unwrapped { "data": ... } or converted key case returned the raw body for delete only. An empty body, or one your process() empties, still becomes the params (#4698)

Validation​

Mistakes are cheapest to fix when TypeScript, a test or a development warning catches them, before a user sees them.

Type safety​

A wrong value that compiles shows up later as bad data or undefined. A cast on correct code hides the next real mistake.

Typed set() values​

react vue

Controller.set() previously accepted any value for a schema, so a typo or a wrong field type only surfaced as bad data at runtime. Values are now typed by the schema: an Entity takes its fields, while a Collection, All or Array takes a list of rows. Every field is optional, since set() merges into what is already stored, and numbers and strings are interchangeable just like in API responses. #4133

Hover the red underlines to see each error.

import type { Controller } from '@data-client/react';
import { schema } from '@data-client/rest';
import { Todo, TodoResource } from './Todo';

export function updateTodos(ctrl: Controller) {
  // ✅ rows are partial Todos; ids may be strings or numbers
  ctrl.set(TodoResource.getList.schema, [{ id: '5', completed: true }]);
  ctrl.set(Todo, { id: 5 }, todo => ({ completed: !todo.completed }));
  ctrl.set([Todo], [{ id: 1, title: 'first' }, { id: 2 }]);

  // ❌ All takes a list of rows
  ctrl.set(new schema.All(Todo), 42);
  // ❌ completed is a boolean
  ctrl.set(Todo, { id: 5 }, { id: 5, completed: 'yes' });
  // ❌ Todo has no done field
  ctrl.set(TodoResource.getList.schema, [{ id: 5, done: true }]);
  // ❌ updaters must return Todo fields
  ctrl.set(Todo, { id: 5 }, todo => ({ title: todo.completed }));
}

A Query takes the input of the schema it wraps, since set() normalizes that schema rather than reversing process(). When each member declares its discriminator as a literal (like readonly type = 'post'), a Union row is checked against the member it selects, so it can't mix fields from different members; see Unions.

If code that previously compiled now fails here, it was writing data its schema doesn't describe. Fix the value, or widen the Entity's field types if the data really can take that shape.

Typed process() params​

rest

A process() method passed to new RestEndpoint(), .extend() or resource().extend() got params typed as any, so reading a parameter the endpoint doesn't have compiled and returned undefined at runtime. params and body are now typed from the endpoint, including a path set in the same .extend() call (#4183, #4184):

import { RestEndpoint } from '@data-client/rest';

const getUser = new RestEndpoint({ path: '/users/:id' });

export const getUserById = getUser.extend({
  path: '/users/by-id/:userId',
  process(value, params) {
    const userId: string | number = params.userId;
    // @ts-expect-error 'id' is not a param of '/users/by-id/:userId'
    params.id;
    return { ...value, userId };
  },
});

When every param is optional, params may be undefined, so read it with params?.page.

This can surface new TypeScript errors in existing process() methods. Each one marks a read that could be undefined or throw at runtime, so fix the param name or add the missing check.

Typed optimistic responses​

rest endpoint graphql

getOptimisticResponse() could return anything unless the endpoint had a typed process(), so a wrong field type only showed up as bad data in the UI until the server responded. The return value is now checked against the endpoint's schema, like a typed set() value: an Entity takes any of its fields, and a Collection takes a list of them (#4198):

import { Entity, RestEndpoint } from '@data-client/rest';

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

export const toggleTodo = new RestEndpoint({
  path: '/todos/:id',
  method: 'PATCH',
  schema: Todo,
  // @ts-expect-error completed is a boolean; 'false' is truthy, so the checkbox would stay checked
  getOptimisticResponse(snap, { id }) {
    const todo = snap.get(Todo, { id });
    if (!todo) throw snap.abort;
    return { id, completed: todo.completed ? 'false' : 'true' };
  },
});

This can surface new TypeScript errors in existing getOptimisticResponse() methods. Each one marks a value that would be stored with the wrong type until the server responds, so return the field's real type (here !todo.completed).

Typed Endpoint signal​

endpoint rest graphql

Every Endpoint now types this.signal, so a wrapped SDK call can cancel without declaring it. Pass it on from the fetch function, and keep it out of the arguments, which are the cache key (#4658):

import { Endpoint, Entity } from '@data-client/rest';

class Post extends Entity {
  id = 0;
  title = '';
}
declare const client: {
  getPosts(options: { page: number; signal?: AbortSignal }): Promise<Post[]>;
};

export const getPosts = new Endpoint(
  function ({ page }: { page: number }) {
    return client.getPosts({ page, signal: this.signal });
  },
  { name: 'getPosts', schema: [Post] },
);

useCancelling() and extend({ signal }) set it.

Fix: FormData in resource().create​

rest

resource()'s create sends a FormData body as-is, like update, partialUpdate and getList.push, but its type only allowed an object, so submitting a form needed a cast (#4235). Drop the cast:

Before
<form
onSubmit={e => {
e.preventDefault();
ctrl.fetch(PostResource.create, new FormData(e.currentTarget) as any);
}}
>
After
<form
onSubmit={e => {
e.preventDefault();
ctrl.fetch(PostResource.create, new FormData(e.currentTarget));
}}
>

create is deprecated; getList.push is its replacement and takes FormData too.

Fix: Union bodies​

rest

A RestEndpoint whose body was typed as a union, like a zod discriminated union or A & (B | C), rejected every value of that union, so calling it needed a cast (#4591). Drop the cast:

Before
type Register = { email: string } & (
{ teamId: string } | { teamName: string }
);

const register = new RestEndpoint({
path: '/auth/register',
method: 'POST',
body: {} as Register,
});

function signUp(ctrl: Controller, input: Register) {
return ctrl.fetch(register, input as any);
}
After
type Register = { email: string } & (
{ teamId: string } | { teamName: string }
);

const register = new RestEndpoint({
path: '/auth/register',
method: 'POST',
body: {} as Register,
});

function signUp(ctrl: Controller, input: Register) {
return ctrl.fetch(register, input);
}

Before v0.19, TypeScript only accepted a body that matched every member of the union at once. A union body added with .extend({ body }) was typed never, so nothing but a cast compiled.

Fix: Entity classes typecheck as EntityInterface​

endpoint rest graphql

Helpers typed to accept any Entity with EntityInterface rejected Entity classes, because Entity.pk() typed its args as a mutable array. It is now readonly any[], so this typechecks (#4149):

import { Entity } from '@data-client/rest';
import type { EntityInterface } from '@data-client/react';

class User extends Entity {
  id = '';
  name = '';
}

function entityName(schema: EntityInterface) {
  return schema.key;
}

entityName(User);

If you override static pk() and type args as a mutable array, it still compiles, but a future breaking release will require readonly; update it now.

Other type changes​

  • react vue useQuery() accepts null to skip, like the other hooks, so useQuery(Todo, id ? { id } : null) typechecks and returns undefined until id is set (#4661)
  • react vue Fix: A Controller subclass passed to DataProvider or DataClientPlugin no longer needs a cast to type-check (#4228)
  • react Fix: prepareStore()'s store can be passed to react-redux's <Provider> without a cast, and has dispatch() in its type (#4238)
  • rest Fix: resource().extend() with an object of endpoint overrides keeps endpoints added earlier with .extend('name', options) in its type, so using them is no longer a TypeScript error (#4184)
  • rest Fix: Conditional fetching works for a RestEndpoint without path or search params: it accepts {}, so useSuspense(getTeams, showTeams ? {} : null) is no longer a TypeScript error (#4612)
  • react vue Fix: A FETCH action's meta.promise is typed Promise, so a Manager can call .finally() and .catch() on it. It was typed PromiseLike, which only has .then() (#4227)
  • react vue Fix: ExpiryStatus compiles with TypeScript's isolatedModules (the default in Vite and Next.js apps), instead of failing with TS2748: Cannot access ambient const enums (#4671)
  • endpoint rest graphql Fix: Editor hover docs for Entity.maxEntityDepth show its real default, 64, not 128 (#4224)

Fix: TypeScript 4.0–4.5 and 7​

all

  • Fix TypeScript 7 module resolution for package exports; imports now resolve to declaration files (#4019)
  • Fix Cannot find name 'NoInfer' and export type errors on TypeScript 4.x with skipLibCheck off (#4138)
  • Fix Entity, Endpoint, Union and RestEndpoint type errors on TypeScript 4.0–4.5 with skipLibCheck off (#4140)
  • Fix ',' expected errors importing @data-client/react/redux, @data-client/react/nextjs or @data-client/test on TypeScript 4.0–4.4 (#4232)
  • Fix act and renderHook from @data-client/test typed as any on TypeScript 4.0–4.4 (#4251)

Testing​

A test that hangs, or passes while still suspended, hides real bugs.

  • test renderDataHook() works with React Native Testing Library 14 and stays synchronous, so renderDataHook() calls need no await (#4374)
  • test react vue Fixtures honor the fetch's AbortSignal, rejecting with an AbortError like fetch(), and fetchResponse() interceptors can be async (#4516)
  • test Fix: renderDataHook() takes a managers option, so a test can run its own Manager; before, the option was ignored (#4602)
  • test Fix: renderDataHook() runs provider mount effects when the first render suspends (#4099)
  • test Fix: Fixtures for a plain Endpoint in renderDataHook() or MockResolver resolve controller.fetch() instead of hanging (#4625)
  • react Fix: DataProvider renders in Vitest 2 tests with the jsdom environment and Vitest's default config, so you can remove a server.deps.inline workaround; before, it threw useEnhancedReducer is not a function (#4613)
  • react rest Fix: In Vitest and other Node ESM setups without a bundler, hooks now see the providers from @data-client/react/redux, /ssr and /nextjs. Before, they acted as if no provider was rendered: they logged "It appears you are trying to use Reactive Data Client without a provider" and fetched nothing. Subpaths now share the main entry's code, so a test that imports one, in Vitest or Jest, loads up to 72% less data-client code. Browser bundles don't change (#4626)
  • test react vue Fix: Fixtures written with args: [...] as const type-check in MockResolver, renderDataHook(), Vue's renderDataCompose() and mockInitialState() (#4250)
  • test react Fix: Fixture types no longer need @data-client/endpoint installed, so projects with only @data-client/react and @data-client/test (for example with pnpm's strict layout) type-check (#4420)
  • vue Fix: @data-client/vue/test loads in Jest and Node. Before, require() threw Cannot find module, and Node's import left mountDataClient, renderDataCompose and MockPlugin undefined (#4617)

Development warnings​

A warning should fire only for a real problem, and say how to fix it.

  • react vue When getOptimisticResponse() returns an Entity without its primary key, development builds log a short Optimistic update skipped error once with the likely fix, instead of a long processing error on every store update (#4616)
  • react The "Uncaught suspense" warning says to put Suspense boundaries inside DataProvider, since one above it never catches (#4609)
  • rest When a mutation's getRequestInit() returns no method, development builds log an error, since fetch() would send a GET. This catches an override that spreads super.getRequestInit() without await (#4647)
  • react Fix: DataProvider only warns that it doesn't update during SSR when something fetches while the server renders, instead of on every server render, so pages that load data after mount (like Expo Router's static web output) stay quiet (#4449)
  • react Fix: Server rendering with React 19 no longer logs "Uncaught suspense" when nothing suspended; React renders and discards fallbacks of large boundaries, and the warning now waits for a fallback that actually shows (#4450)

Migration guide​

This upgrade requires updating all package versions simultaneously.

npm install --save @data-client/react@^0.19.0 @data-client/rest@^0.19.0 @data-client/endpoint@^0.19.0 @data-client/core@^0.19.0 @data-client/vue@^0.19.0 @data-client/test@^0.19.0 @data-client/img@^0.19.0
Ejecútalo en tu terminal

The codemods now ship as the @data-client/codemods package, so npx @data-client/codemods v0.19 src/ runs the codemod for this release (#4409).

Using an AI agent? Install the migration skill. It runs the codemod and fixes what it flags:

npx skills add reactive/data-client --skill data-client-v0.19-migration
Ejecútalo en tu terminal

For all users​

Next.js Pages Router is not supported​

react

Skip this section if you use the Next.js App Router, or don't use Next.js.

@data-client/ssr only supports @data-client/react up to 0.14, so the Pages Router (pages/_document and pages/_app with DataClientDocument and AppDataProvider) doesn't work with 0.19. Move to the App Router, and render DataProvider from @data-client/react/nextjs in your root layout:

app/layout.tsx
import { DataProvider } from '@data-client/react/nextjs';

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

Then uninstall @data-client/ssr, and @data-client/redux if nothing else uses it.

TypeScript 4.0 or later​

all

Skip this section if you already use TypeScript 4.0 or later.

The TypeScript 3.x declarations are removed, since they no longer typechecked on any TypeScript 3.x version. Bump typescript to ^4.0.0 or later in your devDependencies. #4151

managers is a function​

react vue

Skip this section if you don't pass managers to DataProvider, DataClientPlugin or prepareStore().

managers takes a function instead of an array. DataProvider calls it once for each store, so a remounted DataProvider gets new Managers. Before, every store that used an array shared its instances, and state about the old store leaked into the new one. Define the function at module level, and create each Manager inside it. A Manager's constructor stores only its options; see Manager lifetimes for what goes where.

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

<DataProvider managers={managers}>
After
const managers = () => [new MyManager(), ...getDefaultManagers()];

<DataProvider managers={managers}>

The v0.19 codemod converts arrays, getDefaultManagers(), Vue's plugin options and the managers of renderDataHook() and renderDataCompose(). Where it can only wrap an array defined elsewhere as () => managers, it adds a TODO(data-client) comment: move the new calls into the function so stores don't share instances.

npx @data-client/codemods v0.19 src/
Ejecútalo en tu terminal

Custom providers drop initManager()'s third argument, since init() gets the store's current state. The codemod does this too. #4601

Controller.fetchIfStale() always returns a Promise​

react vue

Controller.fetchIfStale() now always returns a Promise of the latest fetch's outcome, and fetches only when the cache is stale. A call you don't await can't reject unhandled, because the error is already stored like any fetch error, so components reading that endpoint handle it as usual.

QuestionBeforeAfter
What does the call return?The data when fresh, a Promise when staleAlways a Promise
An unawaited call's fetch fails. What happens?Unhandled rejectionNo unhandled rejection; the error is stored, as before
What does await give when the latest fetch failed within errorExpiryLength?undefinedRejects with that error
How do I check freshness without fetching?Check the result with instanceof PromisegetResponse()
async function issueLoader(ctrl: Controller, id: number) {
// start the comments request without waiting for it; no .catch() needed
ctrl.fetchIfStale(CommentResource.getList, { issueId: id });
// wait for the issue; rejects if its fetch fails
await ctrl.fetchIfStale(IssueResource.get, { id });
}

Before, a loader that started a prefetch with .catch() threw a TypeError on a second visit, because fresh data came back synchronously and had no .catch(). Without .catch(), a failed prefetch was an unhandled rejection, which crashes Node in server-side loaders. No natural way to write a prefetch was safe.

Why each decision:

  • Always a Promise. fetchIfStale() first returned undefined for fresh data (#2743). #2745 returned the cached data instead, so that await fetchIfStale() resolves the data either way. The synchronous value was a side effect of that fix, and await still works. One call can't return plain data and also support .catch(). The old return type was a union, so typed code already checked instanceof Promise or awaited before using it, and router loaders (React Router, TanStack Router) await whatever they get. await takes one microtask on plain data and on a resolved Promise alike, so awaiting callers see no extra delay.
  • Unawaited calls never reject unhandled. The error is already stored for the components that read the endpoint, so an unhandled copy adds only a crash. Calls that await still reject. A separate non-rejecting prefetch() method would have kept fetchIfStale().catch() broken, and that is the code people and agents write.
  • await rejects when the latest fetch failed within errorExpiryLength. The Promise reports the latest fetch's outcome, and that fetch failed, so it rejects like useSuspense() throws the same error. Before, it resolved undefined, so code that awaited and then read a field crashed.

To check whether data is cached and fresh without fetching, read getResponse() synchronously. It runs the same check fetchIfStale() does:

const { data, expiryStatus, expiresAt } = ctrl.getResponse(
IssueResource.get,
{ id },
ctrl.getState(),
);
const fresh = expiryStatus !== ExpiryStatus.Invalid && Date.now() <= expiresAt;

What to check when upgrading. The v0.19 codemod handles the first three:

npx @data-client/codemods v0.19 src/
Ejecútalo en tu terminal
  • Code that reads the result as data, such as instanceof Promise, .title, destructuring or an if on it: await it (below). Where an instanceof Promise or isPromise() check has a branch that awaits the result and reads the data (or the other branch is empty), the codemod keeps that branch and deletes the other. It adds a TODO(data-client) comment above each other read it finds. The type checker flags property reads it misses, like results passed through other functions.
  • Tests that mock the old return: spyOn(ctrl, 'fetchIfStale').mockReturnValue(data) becomes .mockResolvedValue(data), and fetchIfStale: jest.fn(() => data) resolves its value.
  • Promise.resolve(ctrl.fetchIfStale(...)) wrappers are no longer needed, and the codemod removes them, along with a no-op .catch(() => {}) on a call you don't await.
  • Error monitoring: failures of calls you don't await no longer reach global unhandled-rejection handlers: the browser console's "Uncaught (in promise)" error, error trackers that capture unhandled rejections (like Sentry), and Node's unhandledRejection event. The same now holds for reads you don't await with fetch() (below). To report every failed fetch, awaited or not, add an error reporting Manager.
  • Loaders that await it now reject when the latest fetch failed within errorExpiryLength, as they already did when a stale fetch failed, so the router's error UI shows the error instead of the component's error boundary. To keep waiting but leave the error to the component, add .catch(() => {}) to that call. Code that handled a missing result after await, like ?? fallback, gets a TODO(data-client) comment from the codemod: move that handling into .catch().
  • .then() chains: a .then() on the result makes a new Promise, so end the chain with .catch() as usual.
  • Controller subclasses that override fetchIfStale() must return a Promise.
Before
const issue = ctrl.fetchIfStale(IssueResource.get, { id });
if (!(issue instanceof Promise)) render(issue);
After
const issue = await ctrl.fetchIfStale(IssueResource.get, { id });
render(issue);

#4657

Unawaited reads with Controller.fetch() never reject unhandled​

react

Controller.fetch() of an endpoint without sideEffect (a read) now works like fetchIfStale(): a call you don't await can't reject unhandled, because its error is stored for the components that read that endpoint. await and .catch() still get the error. Mutations (sideEffect: true) still reject unhandled. Nothing breaks, so this is not a breaking change, but it lets you delete code and changes what error trackers see.

Why each decision:

  • Reads only. A read's error already has a reader: the components that render that endpoint. An unhandled copy only adds a crash in Node server loaders, or a warning in React Native. A mutation's error has no other reader, so its rejection stays the signal that a write failed.
  • In fetch(), not in each caller. Every caller had to remember .catch(() => {}). The library itself missed it in the React Native refetch on screen focus of useSuspense(), useDLE() and useFetch(), which warned on every failed refetch.

What to check when upgrading:

  • .catch(() => {}) on reads you don't await is no longer needed; delete it. Keep a catch that does something, catches on mutations, and catches that end a .then() chain, since .then() returns a new Promise. The v0.19 codemod deletes it on fetch() of a resource's get, getList or getList.getPage when nothing uses the result.
  • Error reporting (optional): a failed read you don't await no longer reaches global unhandled-rejection handlers, such as Sentry's default setup. Fetches started by hooks never did. To send every failed fetch to Sentry or another tracker, add an error reporting Manager.
  • A read no component renders, like a "load more" button's getPage: nothing shows its error, so wrap the call in useLoading() or await it.
  • A hand-written Endpoint that changes data needs sideEffect: true, as before; without it, its failures now go quiet too.
Before
// .catch() kept a failed refresh from rejecting unhandled
const refresh = () => ctrl.fetch(TodoResource.getList).catch(() => {});
After
// the error is stored for the components rendering the list
const refresh = () => ctrl.fetch(TodoResource.getList);

#4670

__DC_CONTROLLERS__ is now __DC__​

react vue

Skip this section if no debugging script or tool of yours reads globalThis.__DC_CONTROLLERS__.

In development, DevToolsManager now puts the store on globalThis.__DC__, whose controller and actions read the page's store, instead of the __DC_CONTROLLERS__ Map. With several stores, __DC__.stores lists their keys and setting __DC__.store picks one.

Before
__DC_CONTROLLERS__.get('Data Client: My App').getState();
After
__DC__.store = 'Data Client: My App'; // only needed with several stores
__DC__.controller.getState();

The v0.19 codemod makes this change in the JavaScript and TypeScript files you pass it, including scripts that don't import Data Client, and adds a TODO(data-client) comment on other uses of __DC_CONTROLLERS__. Those include code that handles a missing store, since __DC__.controller throws where .get(name) returned undefined. #4393, #4435

For custom Manager authors​

Manager.middleware is required​

react vue

Skip this section if your Managers already define middleware.

getMiddleware() was replaced by the middleware property in v0.14; it's now removed. A Manager that still defines it, or has no middleware at all, is a TypeScript error, and throws when DataProvider or DataClientPlugin mounts in development. Rename getMiddleware() to a middleware property. The v0.19 codemod does this when getMiddleware() only returns a function, and gives a Manager without middleware a pass-through. Where it can't convert safely, such as super.getMiddleware(), it leaves the code and adds a TODO(data-client) comment:

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

cleanup() {}
}
After
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() {}
}

#4382

Manager cleanup() no longer means the store is gone​

react

Skip this section if your custom Managers start no timers, connections or listeners.

cleanup() now pauses a Manager. It does not end the store. DataProvider runs init() and cleanup() like an Effect's setup and cleanup. So React StrictMode, and <Activity> hiding a DataProvider, call cleanup() and later init() on the same store. The store keeps applying actions in between. Start timers and connections in init(), and stop them in cleanup(). Don't reset state about the store in cleanup(). Actions can still arrive after cleanup(), so guard side effects with a field cleanup() clears, like this.channel?.postMessage(). init() gets the store's current state, including on resume.

Before
class TimeManager implements Manager {
declare protected intervalID?: ReturnType<typeof setInterval>;

middleware: Middleware = controller => {
this.intervalID = setInterval(() => {
controller.set(CurrentTime, { id: 1 }, { id: 1, time: Date.now() });
}, 1000);
return next => async action => next(action);
};

cleanup() {
clearInterval(this.intervalID);
}
}
After
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);
}
}

On React 18 and later, an unmounted DataProvider now passes actions to its Managers, so its fetch() is sent. React ignores the store update, so promises that wait for it never resolve: set(), setResponse(), resetEntireStore(), and fetch() of an endpoint without sideEffect. Don't await them after unmount. React 16 and 17 still drop these actions. NetworkManager.cleanupDate is removed, since nothing reads it. Delete code that reads or sets it; the v0.19 codemod adds a TODO(data-client) comment above each use. #4593

For test authors​

@data-client/test requires @data-client/react 0.19​

test

Skip this section if you don't use @data-client/test.

Support for @data-client/react 0.12 through 0.18 is dropped. Upgrade @data-client/react to the same version as @data-client/test, as the install command above does. Fixture types imported from @data-client/test and from @data-client/react/mock are now the same types. #4414

makeRenderDataHook() now passes managers to its Provider as a function, the form 0.19 recommends. A custom Provider must accept managers: () => Manager[], as DataProvider does. #4601

renderDataHook() used to ignore its managers option and always run a NetworkManager and a SubscriptionManager. Now the list you pass replaces them, and renderDataHook() throws if it has no NetworkManager. To keep tests running as before, the v0.19 codemod adds both to a managers list of new Managers that lacks them. #4602

React Native tests need @testing-library/react-native​

test

React Native projects testing with @data-client/test need @testing-library/react-native installed. #4595

Get ready for future releases​

Nothing here is needed to upgrade to 0.19; your code keeps working as is. Each item will break in a future release, so updating now makes that upgrade a no-op. The v0.19 codemod also moves off older deprecated APIs: it renames the DevTools actionsBlacklist / actionsWhitelist options to actionsDenylist / actionsAllowlist, renames resource().create to getList.push where the endpoint is run (for a resource declared in the file or imported from a relative path or tsconfig alias), makes the two changes below, and adds a TODO(data-client) comment on the rest. Pass --deprecations=only to do this in its own commit, after --deprecations=false for the upgrade. #4669

Entity.pk() args are readonly​

endpoint rest graphql

Skip this if you don't override static pk() with a typed args parameter.

Entity.pk() now types args as readonly any[]. Overrides that annotate it as a mutable array still compile for now, but a future release will require readonly. The v0.19 codemod makes this change, and adds a TODO(data-client) comment where the override changes args or types it with a named type.

Before
class User extends Entity {
static pk(value: any, parent?: any, key?: string, args?: any[]) {
return `${value.id}-${args?.[0]?.org}`;
}
}
After
class User extends Entity {
static pk(value: any, parent?: any, key?: string, args?: readonly any[]) {
return `${value.id}-${args?.[0]?.org}`;
}
}

Vue createDataClient()​

vue

Skip this if you install the store with app.use(DataClientPlugin).

createDataClient() and ProvidedDataClient are internal to DataClientPlugin and will stop being exported. Install the plugin instead, and read the controller with useController(). #4193

Before
import { createDataClient } from '@data-client/vue';

const { controller } = createDataClient({ managers, initialState });
After
import { DataClientPlugin, useController } from '@data-client/vue';

app.use(DataClientPlugin, { managers, initialState });
// in a component's setup()
const controller = useController();

Vue renderDataCompose() waitForNextUpdate()​

vue

Skip this if your Vue tests don't call waitForNextUpdate().

waitForNextUpdate() from renderDataCompose() gives up silently after 1 second, so a test can pass while the composable is still suspended. It will be removed. await the result instead, and call allSettled() after changing props or calling the controller; it now also waits for the fetch a prop change starts. The v0.19 codemod makes this change. Right after the render, it deletes the wait when the next line awaits result, and otherwise adds a TODO(data-client) comment, since the old call also waited for a Promise result. #4221

Before
const { result, waitForNextUpdate } = await renderDataCompose(
(props: { id: number }) =>
useSuspense(ArticleResource.get, () => ({ id: props.id })),
{ props, resolverFixtures },
);
await waitForNextUpdate();
const article = await result;

props.id = 6;
await waitForNextUpdate();
After
const { result, allSettled } = await renderDataCompose(
(props: { id: number }) =>
useSuspense(ArticleResource.get, () => ({ id: props.id })),
{ props, resolverFixtures },
);
const article = await result;

props.id = 6;
await allSettled();

Adopt new features​

Optional once you're on 0.19. Run the codemod in its own commit:

npx @data-client/codemods v0.19 src/ --improvements=only
Ejecútalo en tu terminal

It batches ctrl.set() loops into one batch set(), and drops code 0.19 makes unnecessary: one-row deletes, Vue's default gcPolicy and computed() args, and typeof data === 'symbol' checks. After batching, a Manager matching SET actions by action.schema sees [Ticker] instead of Ticker (#4697).

Upgrade support​

As usual, if you have any troubles or questions, feel free to join our Chat or file a bug