@molecule/app-query-react 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-11-12T06:19:59.085Z
6
+ Generated: 2026-11-12T14:06:05.610Z
7
7
  -->
8
8
 
9
9
  # @molecule/app-query-react
@@ -29,6 +29,13 @@ This package needs a bonded client: install `@molecule/app-query` with a bond
29
29
  (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
30
30
  `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
31
31
 
32
+ **Keep displayed records on the query cache.** Render `query.data` directly. A custom
33
+ mutation handler publishes its saved response with `query.setData(saved)`; every observer
34
+ and the next visit receive it, and subsequent refreshes still update the view. A local
35
+ `useState` copy hydrated only once per record hides later query answers. Editable form
36
+ drafts remain local until saved. Prefer {@link createQueryResource} for a complete resource;
37
+ its writes already publish the response and refresh its tracked collections.
38
+
32
39
  > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
33
40
  > It is written to be read by coding agents as much as by people, and is generated from this
34
41
  > package's source — edit `src/index.ts` JSDoc, not this file.
@@ -268,6 +275,38 @@ function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
268
275
  }
269
276
  ```
270
277
 
278
+ A pager needs the whole response, including its total. Keep that read on the same resource
279
+ as its mutations, including alternate list paths; a separate hand-written `QueryOptions`
280
+ is outside the resource's refresh tracking.
281
+
282
+ ```typescript
283
+ import { getClient } from '@molecule/app-http'
284
+ import { createQueryResource } from '@molecule/app-query-react'
285
+
286
+ interface TicketPage {
287
+ tickets: { id: string; subject: string }[]
288
+ total: number
289
+ }
290
+ const tickets = createQueryResource<TicketPage['tickets'][number]>({
291
+ name: 'tickets',
292
+ path: '/tickets',
293
+ http: getClient,
294
+ readOne: (response) => response.data as TicketPage['tickets'][number],
295
+ })
296
+ const page = tickets.listPage(
297
+ 'agent-1',
298
+ { limit: 10, offset: 20 },
299
+ (response) => response.data as TicketPage,
300
+ )
301
+ // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
302
+ // and tickets.refresh('agent-1') refresh this page too.
303
+ // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
304
+ // Use one canonical page reader per path; list() still returns only its own rows.
305
+ ```
306
+
307
+ A resource mutation also waits out a pre-mutation list request before fetching again;
308
+ joining that older in-flight read alone would leave the new record absent.
309
+
271
310
  ## Type
272
311
 
273
312
  `feature`
@@ -351,6 +390,17 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
351
390
  * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
352
391
  */
353
392
  list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
393
+ /**
394
+ * Options for a collection's whole page (rows plus totals), or a filtered collection path.
395
+ * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
396
+ * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
397
+ */
398
+ listPage<Page>(
399
+ viewer: string,
400
+ params: Record<string, unknown>,
401
+ readPage: (response: ResourceResponse) => Page,
402
+ path?: string,
403
+ ): QueryOptions<Page>
354
404
  /**
355
405
  * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
356
406
  * observes nothing). A missing record resolves to null, not to an error.
@@ -375,10 +425,20 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
375
425
 
376
426
  #### `UseQueryResult`
377
427
 
378
- A mounted query's state and its explicit refresh action.
428
+ A mounted query's state and its explicit cache and refresh actions.
379
429
 
380
430
  ```typescript
381
431
  interface UseQueryResult<T> extends QueryState<T> {
432
+ /**
433
+ * Publish a saved document to this key and all its observers. Render `data` directly
434
+ * instead of copying it to local state: later cache updates then remain visible.
435
+ * A function receives this key's current cached document, never retained previous-page
436
+ * data. Returning `undefined` leaves the cache unchanged. A disabled (`null`) query
437
+ * does nothing, including not calling an updater. Like React state setters, wrap a
438
+ * function-valued document in an updater. A saved callback stays bound to its original key.
439
+ * The write supersedes older in-flight reads, using the bonded client's `set` contract.
440
+ */
441
+ setData: (value: T | ((previous: T | undefined) => T | undefined)) => void
382
442
  /**
383
443
  * Fetch this key again, even when its cached document is fresh. Observers receive the
384
444
  * updated state. Resolves with that state, including an error when the request fails;
@@ -493,13 +553,18 @@ account switch then drops the previous account's document immediately. Only
493
553
  an endpoint that answers every viewer the same takes a viewer-free key with
494
554
  `principal: 'public'`.
495
555
 
556
+ For custom mutation handlers, `setData(saved)` publishes the server's response to this
557
+ key and every observer. Use `setData(current => next)` for a local cache update. Render
558
+ `data` directly; a component-local copy stops observing later server responses. Prefer
559
+ `createQueryResource` when the API's reads and writes can share one resource definition.
560
+
496
561
  ```typescript
497
562
  function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
498
563
  ```
499
564
 
500
565
  - `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`.
501
566
 
502
- **Returns:** The document's state and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
567
+ **Returns:** The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
503
568
 
504
569
  ## Injection Notes
505
570
 
@@ -578,7 +643,7 @@ Peer dependencies:
578
643
  - After a mutation, `client.set(key, response)` paints the server's own
579
644
  answer at once and supersedes an older fetch already in flight for that
580
645
  key, so its response cannot undo the mutation. An existing `fetch()` caller
581
- still settles with its older response or a bond-specific cancellation.
646
+ still settles independently of the cache write; read `client.get(key)` for the newest document.
582
647
  `client.invalidate(prefix)` marks the affected reads stale for their next
583
648
  mount. Which key and which scope is the app's decision: the cache does not
584
649
  infer it from auth or form state.
package/dist/index.d.ts CHANGED
@@ -20,6 +20,13 @@
20
20
  * (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
21
21
  * `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
22
22
  *
23
+ * **Keep displayed records on the query cache.** Render `query.data` directly. A custom
24
+ * mutation handler publishes its saved response with `query.setData(saved)`; every observer
25
+ * and the next visit receive it, and subsequent refreshes still update the view. A local
26
+ * `useState` copy hydrated only once per record hides later query answers. Editable form
27
+ * drafts remain local until saved. Prefer {@link createQueryResource} for a complete resource;
28
+ * its writes already publish the response and refresh its tracked collections.
29
+ *
23
30
  * @example
24
31
  * ```tsx
25
32
  * import { Link } from 'react-router'
@@ -244,6 +251,30 @@
244
251
  * }
245
252
  * ```
246
253
  *
254
+ * @example
255
+ * A pager needs the whole response, including its total. Keep that read on the same resource
256
+ * as its mutations, including alternate list paths; a separate hand-written `QueryOptions`
257
+ * is outside the resource's refresh tracking.
258
+ *
259
+ * ```typescript
260
+ * import { getClient } from '@molecule/app-http'
261
+ * import { createQueryResource } from '@molecule/app-query-react'
262
+ *
263
+ * interface TicketPage { tickets: { id: string; subject: string }[]; total: number }
264
+ * const tickets = createQueryResource<TicketPage['tickets'][number]>({
265
+ * name: 'tickets', path: '/tickets', http: getClient,
266
+ * readOne: (response) => response.data as TicketPage['tickets'][number],
267
+ * })
268
+ * const page = tickets.listPage('agent-1', { limit: 10, offset: 20 },
269
+ * (response) => response.data as TicketPage)
270
+ * // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
271
+ * // and tickets.refresh('agent-1') refresh this page too.
272
+ * // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
273
+ * // Use one canonical page reader per path; list() still returns only its own rows.
274
+ * ```
275
+ * A resource mutation also waits out a pre-mutation list request before fetching again;
276
+ * joining that older in-flight read alone would leave the new record absent.
277
+ *
247
278
  * @remarks
248
279
  * - **`useQuery` reads the cache synchronously on the first render.** A
249
280
  * document prefetched from a hovered link, or seeded with `client.set()`
@@ -308,7 +339,7 @@
308
339
  * - After a mutation, `client.set(key, response)` paints the server's own
309
340
  * answer at once and supersedes an older fetch already in flight for that
310
341
  * key, so its response cannot undo the mutation. An existing `fetch()` caller
311
- * still settles with its older response or a bond-specific cancellation.
342
+ * still settles independently of the cache write; read `client.get(key)` for the newest document.
312
343
  * `client.invalidate(prefix)` marks the affected reads stale for their next
313
344
  * mount. Which key and which scope is the app's decision: the cache does not
314
345
  * infer it from auth or form state.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4TG;AAEH,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2VG;AAEH,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
package/dist/index.js CHANGED
@@ -20,6 +20,13 @@
20
20
  * (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
21
21
  * `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
22
22
  *
23
+ * **Keep displayed records on the query cache.** Render `query.data` directly. A custom
24
+ * mutation handler publishes its saved response with `query.setData(saved)`; every observer
25
+ * and the next visit receive it, and subsequent refreshes still update the view. A local
26
+ * `useState` copy hydrated only once per record hides later query answers. Editable form
27
+ * drafts remain local until saved. Prefer {@link createQueryResource} for a complete resource;
28
+ * its writes already publish the response and refresh its tracked collections.
29
+ *
23
30
  * @example
24
31
  * ```tsx
25
32
  * import { Link } from 'react-router'
@@ -244,6 +251,30 @@
244
251
  * }
245
252
  * ```
246
253
  *
254
+ * @example
255
+ * A pager needs the whole response, including its total. Keep that read on the same resource
256
+ * as its mutations, including alternate list paths; a separate hand-written `QueryOptions`
257
+ * is outside the resource's refresh tracking.
258
+ *
259
+ * ```typescript
260
+ * import { getClient } from '@molecule/app-http'
261
+ * import { createQueryResource } from '@molecule/app-query-react'
262
+ *
263
+ * interface TicketPage { tickets: { id: string; subject: string }[]; total: number }
264
+ * const tickets = createQueryResource<TicketPage['tickets'][number]>({
265
+ * name: 'tickets', path: '/tickets', http: getClient,
266
+ * readOne: (response) => response.data as TicketPage['tickets'][number],
267
+ * })
268
+ * const page = tickets.listPage('agent-1', { limit: 10, offset: 20 },
269
+ * (response) => response.data as TicketPage)
270
+ * // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
271
+ * // and tickets.refresh('agent-1') refresh this page too.
272
+ * // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
273
+ * // Use one canonical page reader per path; list() still returns only its own rows.
274
+ * ```
275
+ * A resource mutation also waits out a pre-mutation list request before fetching again;
276
+ * joining that older in-flight read alone would leave the new record absent.
277
+ *
247
278
  * @remarks
248
279
  * - **`useQuery` reads the cache synchronously on the first render.** A
249
280
  * document prefetched from a hovered link, or seeded with `client.set()`
@@ -308,7 +339,7 @@
308
339
  * - After a mutation, `client.set(key, response)` paints the server's own
309
340
  * answer at once and supersedes an older fetch already in flight for that
310
341
  * key, so its response cannot undo the mutation. An existing `fetch()` caller
311
- * still settles with its older response or a bond-specific cancellation.
342
+ * still settles independently of the cache write; read `client.get(key)` for the newest document.
312
343
  * `client.invalidate(prefix)` marks the affected reads stale for their next
313
344
  * mount. Which key and which scope is the app's decision: the cache does not
314
345
  * infer it from auth or form state.
@@ -53,6 +53,12 @@ export interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
53
53
  * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
54
54
  */
55
55
  list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>;
56
+ /**
57
+ * Options for a collection's whole page (rows plus totals), or a filtered collection path.
58
+ * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
59
+ * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
60
+ */
61
+ listPage<Page>(viewer: string, params: Record<string, unknown>, readPage: (response: ResourceResponse) => Page, path?: string): QueryOptions<Page>;
56
62
  /**
57
63
  * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
58
64
  * observes nothing). A missing record resolves to null, not to an error.
@@ -1 +1 @@
1
- {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAY,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGjE,qDAAqD;AACrD,MAAM,WAAW,gBAAgB;IAC/B,gCAAgC;IAChC,IAAI,EAAE,OAAO,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AE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAC7D,mFAAmF;IACnF,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACjD;;;;OAIG;IACH,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAC3E,2FAA2F;IAC3F,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CACvC;AAKD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,EAC7E,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC,GAC7B,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAqGlC"}
package/dist/resource.js CHANGED
@@ -34,6 +34,14 @@ export function createQueryResource(config) {
34
34
  // The lists handed out most recently, newest last: the ones a write fetches again. A list
35
35
  // nobody reads any more costs one request and is then dropped by the next ones.
36
36
  const recent = new Map();
37
+ const track = (viewer, options) => {
38
+ const hash = hashQueryKey(options.key);
39
+ recent.delete(hash);
40
+ recent.set(hash, { viewer, options });
41
+ for (const stale of [...recent.keys()].slice(0, -REFRESHED_LISTS))
42
+ recent.delete(stale);
43
+ return options;
44
+ };
37
45
  const list = (viewer, params = {}) => {
38
46
  const options = {
39
47
  key: [config.name, viewer, 'list', params],
@@ -41,22 +49,26 @@ export function createQueryResource(config) {
41
49
  keepPreviousData: true,
42
50
  fetch: async (signal) => readList(await config.http().get(base, { signal, params })),
43
51
  };
44
- const hash = hashQueryKey(options.key);
45
- recent.delete(hash);
46
- recent.set(hash, { viewer, options });
47
- for (const stale of [...recent.keys()].slice(0, -REFRESHED_LISTS))
48
- recent.delete(stale);
49
- return options;
52
+ return track(viewer, options);
50
53
  };
51
54
  const refresh = async (viewer) => {
52
55
  const client = getQueryClient();
53
56
  client.invalidate([config.name, viewer, 'list']);
54
57
  await Promise.all([...recent.values()]
55
58
  .filter((entry) => entry.viewer === viewer)
56
- .map((entry) => client.fetch(entry.options).catch((_error) => {
57
- // The mounted `useQuery` of that list presents its own failure as `status: 'error'`;
58
- // the write that asked for this refresh succeeded and must not reject over it.
59
- })));
59
+ .map(async (entry) => {
60
+ // fetch() deduplicates an existing request. It may have read before this write,
61
+ // so joining it alone cannot refresh the list after the mutation.
62
+ const pending = client.getState(entry.options.key).isFetching;
63
+ const fetch = () => client.fetch(entry.options).catch((_error) => {
64
+ // The mounted query presents its own failure; the mutation already succeeded.
65
+ });
66
+ await fetch();
67
+ if (pending) {
68
+ client.invalidate(entry.options.key);
69
+ await fetch();
70
+ }
71
+ }));
60
72
  };
61
73
  const saved = async (viewer, response) => {
62
74
  const record = readOne(response);
@@ -70,6 +82,12 @@ export function createQueryResource(config) {
70
82
  };
71
83
  return {
72
84
  list,
85
+ listPage: (viewer, params, readPage, path = base) => track(viewer, {
86
+ key: [config.name, viewer, 'list', 'page', path, params],
87
+ principal: viewer,
88
+ keepPreviousData: true,
89
+ fetch: async (signal) => readPage(await config.http().get(path, { signal, params })),
90
+ }),
73
91
  detail: (viewer, id) => id == null || id === ''
74
92
  ? null
75
93
  : {
package/dist/types.d.ts CHANGED
@@ -3,8 +3,18 @@
3
3
  * @module
4
4
  */
5
5
  import type { QueryState } from '@molecule/app-query';
6
- /** A mounted query's state and its explicit refresh action. */
6
+ /** A mounted query's state and its explicit cache and refresh actions. */
7
7
  export interface UseQueryResult<T> extends QueryState<T> {
8
+ /**
9
+ * Publish a saved document to this key and all its observers. Render `data` directly
10
+ * instead of copying it to local state: later cache updates then remain visible.
11
+ * A function receives this key's current cached document, never retained previous-page
12
+ * data. Returning `undefined` leaves the cache unchanged. A disabled (`null`) query
13
+ * does nothing, including not calling an updater. Like React state setters, wrap a
14
+ * function-valued document in an updater. A saved callback stays bound to its original key.
15
+ * The write supersedes older in-flight reads, using the bonded client's `set` contract.
16
+ */
17
+ setData: (value: T | ((previous: T | undefined) => T | undefined)) => void;
8
18
  /**
9
19
  * Fetch this key again, even when its cached document is fresh. Observers receive the
10
20
  * updated state. Resolves with that state, including an error when the request fails;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAErD,+DAA+D;AAC/D,MAAM,WAAW,cAAc,CAAC,CAAC,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAC;IACtD;;;;OAIG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;CACtC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAErD,0EAA0E;AAC1E,MAAM,WAAW,cAAc,CAAC,CAAC,CAAE,SAAQ,UAAU,CAAC,CAAC,CAAC;IACtD;;;;;;;;OAQG;IACH,OAAO,EAAE,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC,GAAG,SAAS,KAAK,CAAC,GAAG,SAAS,CAAC,KAAK,IAAI,CAAA;IAC1E;;;;OAIG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;CACtC"}
@@ -35,9 +35,14 @@ import type { UseQueryResult } from './types.js';
35
35
  * an endpoint that answers every viewer the same takes a viewer-free key with
36
36
  * `principal: 'public'`.
37
37
  *
38
+ * For custom mutation handlers, `setData(saved)` publishes the server's response to this
39
+ * key and every observer. Use `setData(current => next)` for a local cache update. Render
40
+ * `data` directly; a component-local copy stops observing later server responses. Prefer
41
+ * `createQueryResource` when the API's reads and writes can share one resource definition.
42
+ *
38
43
  * @param options - Key, fetch, freshness, and optionally `principal` with
39
44
  * `keepPreviousData`; or `null`.
40
- * @returns The document's state and `refetch()`. `isPreviousData` is `true` while `data` is
45
+ * @returns The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is
41
46
  * the previous key's document for the same principal.
42
47
  * @throws {Error} When `keepPreviousData` is set without `principal` — the
43
48
  * hook cannot tell a route change from a principal switch, so it refuses
@@ -1 +1 @@
1
- {"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,qBAAqB,CAAA;AAGnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAuBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,CAAC,CAAC,CAsF9E"}
1
+ {"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,qBAAqB,CAAA;AAGnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAuBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,CAAC,CAAC,CAkG9E"}
package/dist/useQuery.js CHANGED
@@ -42,9 +42,14 @@ const IDLE = {
42
42
  * an endpoint that answers every viewer the same takes a viewer-free key with
43
43
  * `principal: 'public'`.
44
44
  *
45
+ * For custom mutation handlers, `setData(saved)` publishes the server's response to this
46
+ * key and every observer. Use `setData(current => next)` for a local cache update. Render
47
+ * `data` directly; a component-local copy stops observing later server responses. Prefer
48
+ * `createQueryResource` when the API's reads and writes can share one resource definition.
49
+ *
45
50
  * @param options - Key, fetch, freshness, and optionally `principal` with
46
51
  * `keepPreviousData`; or `null`.
47
- * @returns The document's state and `refetch()`. `isPreviousData` is `true` while `data` is
52
+ * @returns The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is
48
53
  * the previous key's document for the same principal.
49
54
  * @throws {Error} When `keepPreviousData` is set without `principal` — the
50
55
  * hook cannot tell a route change from a principal switch, so it refuses
@@ -60,6 +65,16 @@ export function useQuery(options) {
60
65
  // Options are read once per key: a fresh `fetch` closure every render must
61
66
  // not resubscribe.
62
67
  const stable = useMemo(() => options, [hash]);
68
+ const setData = useCallback((value) => {
69
+ if (!stable)
70
+ return;
71
+ const client = getQueryClient();
72
+ const next = typeof value === 'function'
73
+ ? value(client.get(stable.key))
74
+ : value;
75
+ if (next !== undefined)
76
+ client.set(stable.key, next);
77
+ }, [stable]);
63
78
  const refetch = useCallback(async () => {
64
79
  if (!stable)
65
80
  return IDLE;
@@ -130,5 +145,5 @@ export function useQuery(options) {
130
145
  const client = getQueryClient();
131
146
  return client.subscribe(stable, (value) => setState({ hash, value }));
132
147
  }, [stable, hash]);
133
- return useMemo(() => ({ ...value, refetch }), [value, refetch]);
148
+ return useMemo(() => ({ ...value, setData, refetch }), [value, setData, refetch]);
134
149
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/app-query-react",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "React hooks for @molecule/app-query — read a cached document synchronously, observe it, and prefetch on intent",
5
5
  "homepage": "https://www.molecule.dev/packages/app-query-react",
6
6
  "type": "module",
@@ -40,9 +40,9 @@
40
40
  "react": "^18.0.0 || ^19.0.0"
41
41
  },
42
42
  "devDependencies": {
43
- "@molecule/app-query": "1.1.2",
43
+ "@molecule/app-query": "1.1.3",
44
44
  "@molecule/app-query-memory": "1.0.4",
45
- "@molecule/app-query-tanstack": "1.0.3",
45
+ "@molecule/app-query-tanstack": "1.0.4",
46
46
  "@types/node": "26.6.5",
47
47
  "@types/react": "19.3.0",
48
48
  "@types/react-dom": "19.3.0",