v0.19: Batch Controller.set(), Faster TypeScript
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 />);
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.
More in v0.19:
- Performance: faster Redux DevTools, shorter React Native GC pauses and smaller split bundles
- Client: delete one entity with set(), unawaited reads need no
.catch(),<Activity>above DataProvider, and loading and error fixes - Platforms: React Native 0.87 and Babel 8
- Vue: garbage collection by default, stale-while-revalidate and getter arguments
- Collections: lists of items in every update, and each item shown once
- Validation: typed
set()values,process()params and optimistic responses; testing and warning fixes
- For all users
- The Next.js Pages Router is not supported; use the App Router (#4648)
- TypeScript 4.0 or later is required - the TypeScript 3.x declarations are removed (#4151)
managersis a function that creates each store's Managers;npx @data-client/codemods v0.19 src/converts arrays (#4601)- Controller.fetchIfStale() always returns a Promise, so prefetches need no
.catch()(#4657) __DC_CONTROLLERS__is now__DC__for debugging scripts (#4435)
- For custom Manager authors
- Managers must define
middleware-getMiddleware()is removed (#4378, #4382) - Manager
cleanup()no longer means the store is gone - start timers and connections ininit(), andNetworkManager.cleanupDateis removed (#4593)
- Managers must define
- For test authors
Get ready for future releases:
- Type
argsasreadonlyinEntity.pk()overrides - Use
DataClientPlugininstead of VuecreateDataClient() - Replace
waitForNextUpdate()in Vue tests
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:
ws.onmessage = event => {
const rows = JSON.parse(event.data);
for (const row of rows) {
ctrl.set(Ticker, { product_id: row.product_id }, row);
}
};
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
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.
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]));
}
};
Explore o exemplo coin-app
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.
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.
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.
We measured a release build on an Android emulator, with the median of 5 launches. Web builds don't change.
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.
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).
Hover or tap a cell for exact numbers.
| TS 6 check time | TS 7 check time | TS 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/:idare 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):
ctrl.set([new Invalidate(Todo)], [{ id: '5' }]);
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).
__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:
function TodoDetail({ id }: { id: number }) {
const todo = useCache(TodoResource.get, { id });
if (!todo || typeof todo === 'symbol') return <TodoPlaceholder />;
return <h3>{todo.title.trim()}</h3>;
}
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
reactController.fetch() of an endpoint withoutsideEffectnever 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)reactSupport React<Activity>above DataProvider. Before, hidingDataProviderdropped responses, fetches and subscriptions, which left useSuspense() loading forever. Most apps should still putDataProviderat 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 ownfetchedAtto controller.resolve(); the v0.19 codemod does this where a Manager resolvesaction.endpointunder anactionTypes.FETCHcheck (#4593)reactvueFix: useLoading() clearserrorwhen 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 Vueloadinganderrorfollow the latest call, and a call that settles inside a hidden<Activity>shows its result once visible (#4614)reactvueFix: A cached result no longer keeps showing a nested entity as missing after that entity wasINVALIDornulland becomes valid again (#4460)reactFix: 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)reactFix: ExternalDataProvider and the ReduxDataProviderrender updates dispatched from children's mount Effects, like an optimisticcontroller.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.
reactSupport React Native 0.87. It removedInteractionManager, so apps on it crashed as soon as a component calleduseSuspense(),useFetch()oruseDLE(). On 0.87 and later, Data Client waits for idle time withrequestIdleCallback(), as React Native recommends (#4355)allSupport@babel/runtime8: apps on Babel 8 share their runtime with Data Client instead of installing a second copy. Apps on Babel 7 keep working (#4209)imgSupport@data-client/react0.19 (#4636)reactFix: 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)reactFix: 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)imgFix: Node'simport, and tools that run on it like Vitest, load the ESM build of@data-client/imginstead 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).
import { DataClientPlugin, GCPolicy } from '@data-client/vue';
app.use(DataClientPlugin, { gcPolicy: new GCPolicy() });
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:
import { computed } from 'vue';
const props = defineProps<{ id: number }>();
const article = await useSuspense(
ArticleResource.get,
computed(() => ({ id: props.id })),
);
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
vueExportGCPolicyfrom@data-client/vue, so a customgcPolicyno longer needs@data-client/core(#4143)vueExport__INTERNAL__, like@data-client/react, so tooling can usecreateReducerandinitialStatewithout depending on@data-client/core(#4270)vueFix: useSuspense() and useLive() keep the previous data while new arguments load, instead of returningundefined(#4131)vueFix: useSuspense() and useLive() send fetch errors after arguments change toonErrorCaptured()instead of an unhandled promise rejection (#4135)vueFix: useSuspense(), useDLE() and useFetch() no longer refetch stale data on every store update, so acontroller.set()is not overwritten (#4134)vueFix: useDLE() and useCache() keep expiredinvalidIfStaledata through unrelated store updates instead of getting stuck loading (#4142)vueFix: useFetch() keeps its data from being garbage collected while mounted, like useSuspense(), so a configuredgcPolicyno longer evicts prefetched data that components read later (#4152)vueFix: useFetch() is typed as the read-onlyRefit returns, sopromise.resolved(alwaysundefined) is now a TypeScript error; readpromise.value.resolvedinstead (#4114)vueFix:DataClientPlugininstalls on Vue versions before 3.5 instead of throwingapp.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):
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);
};
}
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:
function addTodos(ctrl: Controller, userId: string, todos: Todo[]) {
for (const todo of todos) {
ctrl.set(TodoResource.getList.schema.push, { userId } as any, todo);
}
}
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).
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);
}
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:
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
pushorunshiftshows once, not twice (#4487). - An update that resolves after a newer refetch of its list still applies to that list
(#4566).
pushadds to the end,removeandmovechange only their item, andgetPageadds 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:
Daily Grind
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 />);Other REST changes
restFix: ADELETEendpoint that declaresbodysends 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, removebodyor setbody: undefined(#4528)restFix: resource()'sdeleteruns yourEndpointclass's process(), or the resource'sprocessoption. Before,deleteset its ownprocess(), which replaced the base class's, so a base class that unwrapped{ "data": ... }or converted key case returned the raw body fordeleteonly. An empty body, or one yourprocess()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:
<form
onSubmit={e => {
e.preventDefault();
ctrl.fetch(PostResource.create, new FormData(e.currentTarget) as any);
}}
>
<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:
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);
}
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
reactvueuseQuery() acceptsnullto skip, like the other hooks, souseQuery(Todo, id ? { id } : null)typechecks and returnsundefineduntilidis set (#4661)reactvueFix: AControllersubclass passed to DataProvider or DataClientPlugin no longer needs a cast to type-check (#4228)reactFix: prepareStore()'sstorecan be passed to react-redux's<Provider>without a cast, and hasdispatch()in its type (#4238)restFix: 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)restFix: Conditional fetching works for a RestEndpoint without path or search params: it accepts{}, souseSuspense(getTeams, showTeams ? {} : null)is no longer a TypeScript error (#4612)reactvueFix: A FETCH action'smeta.promiseis typedPromise, so a Manager can call.finally()and.catch()on it. It was typedPromiseLike, which only has.then()(#4227)reactvueFix:ExpiryStatuscompiles with TypeScript'sisolatedModules(the default in Vite and Next.js apps), instead of failing withTS2748: Cannot access ambient const enums(#4671)endpointrestgraphqlFix: Editor hover docs forEntity.maxEntityDepthshow 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'andexport typeerrors on TypeScript 4.x withskipLibCheckoff (#4138) - Fix
Entity,Endpoint,UnionandRestEndpointtype errors on TypeScript 4.0–4.5 withskipLibCheckoff (#4140) - Fix
',' expectederrors importing@data-client/react/redux,@data-client/react/nextjsor@data-client/teston TypeScript 4.0–4.4 (#4232) - Fix
actandrenderHookfrom@data-client/testtyped asanyon TypeScript 4.0–4.4 (#4251)
Testing
A test that hangs, or passes while still suspended, hides real bugs.
testrenderDataHook() works with React Native Testing Library 14 and stays synchronous, sorenderDataHook()calls need noawait(#4374)testreactvueFixtures honor the fetch's AbortSignal, rejecting with anAbortErrorlikefetch(), and fetchResponse() interceptors can be async (#4516)testFix: renderDataHook() takes amanagersoption, so a test can run its own Manager; before, the option was ignored (#4602)testFix: renderDataHook() runs provider mount effects when the first render suspends (#4099)testFix: Fixtures for a plain Endpoint in renderDataHook() or MockResolver resolvecontroller.fetch()instead of hanging (#4625)reactFix: DataProvider renders in Vitest 2 tests with thejsdomenvironment and Vitest's default config, so you can remove aserver.deps.inlineworkaround; before, it threwuseEnhancedReducer is not a function(#4613)reactrestFix: In Vitest and other Node ESM setups without a bundler, hooks now see the providers from@data-client/react/redux,/ssrand/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)testreactvueFix: Fixtures written withargs: [...] as consttype-check in MockResolver,renderDataHook(), Vue'srenderDataCompose()andmockInitialState()(#4250)testreactFix: Fixture types no longer need@data-client/endpointinstalled, so projects with only@data-client/reactand@data-client/test(for example with pnpm's strict layout) type-check (#4420)vueFix:@data-client/vue/testloads in Jest and Node. Before,require()threwCannot find module, and Node'simportleftmountDataClient,renderDataComposeandMockPluginundefined (#4617)
Development warnings
A warning should fire only for a real problem, and say how to fix it.
reactvueWhen getOptimisticResponse() returns an Entity without its primary key, development builds log a shortOptimistic update skippederror once with the likely fix, instead of a long processing error on every store update (#4616)reactThe "Uncaught suspense" warning says to put Suspense boundaries inside DataProvider, since one above it never catches (#4609)restWhen a mutation's getRequestInit() returns nomethod, development builds log an error, sincefetch()would send a GET. This catches an override that spreadssuper.getRequestInit()withoutawait(#4647)reactFix: 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)reactFix: 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
- Yarn
- pnpm
- esm.sh
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
yarn add @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
pnpm add @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
<script type="importmap">
{
"imports": {
"@data-client/react": "https://esm.sh/@data-client/react@^0.19.0",
"@data-client/rest": "https://esm.sh/@data-client/rest@^0.19.0",
"@data-client/endpoint": "https://esm.sh/@data-client/endpoint@^0.19.0",
"@data-client/core": "https://esm.sh/@data-client/core@^0.19.0",
"@data-client/vue": "https://esm.sh/@data-client/vue@^0.19.0",
"@data-client/test": "https://esm.sh/@data-client/test@^0.19.0",
"@data-client/img": "https://esm.sh/@data-client/img@^0.19.0"
}
}
</script>
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:
- Skills CLI
- OpenSkills
npx skills add reactive/data-client --skill data-client-v0.19-migration
npx openskills install reactive/data-client/.agents/skills/data-client-v0.19-migration
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:
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.
const managers = [new MyManager(), ...getDefaultManagers()];
<DataProvider managers={managers}>
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/
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.
| Question | Before | After |
|---|---|---|
| What does the call return? | The data when fresh, a Promise when stale | Always a Promise |
| An unawaited call's fetch fails. What happens? | Unhandled rejection | No unhandled rejection; the error is stored, as before |
What does await give when the latest fetch failed within errorExpiryLength? | undefined | Rejects with that error |
| How do I check freshness without fetching? | Check the result with instanceof Promise | getResponse() |
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 returnedundefinedfor fresh data (#2743). #2745 returned the cached data instead, so thatawait fetchIfStale()resolves the data either way. The synchronous value was a side effect of that fix, andawaitstill works. One call can't return plain data and also support.catch(). The old return type was a union, so typed code already checkedinstanceof Promiseor awaited before using it, and router loaders (React Router, TanStack Router) await whatever they get.awaittakes 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
awaitstill reject. A separate non-rejectingprefetch()method would have keptfetchIfStale().catch()broken, and that is the code people and agents write. awaitrejects 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 resolvedundefined, 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/
- Code that reads the result as data, such as
instanceof Promise,.title, destructuring or anifon it:awaitit (below). Where aninstanceof PromiseorisPromise()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 aTODO(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), andfetchIfStale: 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
unhandledRejectionevent. The same now holds for reads you don't await withfetch()(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 afterawait, like?? fallback, gets aTODO(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.
const issue = ctrl.fetchIfStale(IssueResource.get, { id });
if (!(issue instanceof Promise)) render(issue);
const issue = await ctrl.fetchIfStale(IssueResource.get, { id });
render(issue);
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 ofuseSuspense(),useDLE()anduseFetch(), 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 onfetch()of a resource'sget,getListorgetList.getPagewhen 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() orawaitit. - A hand-written Endpoint that changes data needs
sideEffect: true, as before; without it, its failures now go quiet too.
// .catch() kept a failed refresh from rejecting unhandled
const refresh = () => ctrl.fetch(TodoResource.getList).catch(() => {});
// the error is stored for the components rendering the list
const refresh = () => ctrl.fetch(TodoResource.getList);
__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.
__DC_CONTROLLERS__.get('Data Client: My App').getState();
__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:
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() {}
}
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() {}
}
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.
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);
}
}
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.
class User extends Entity {
static pk(value: any, parent?: any, key?: string, args?: any[]) {
return `${value.id}-${args?.[0]?.org}`;
}
}
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
import { createDataClient } from '@data-client/vue';
const { controller } = createDataClient({ managers, initialState });
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
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();
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
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 or file a bug
