@molecule/app-query-react 1.2.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-11T18:03:13.387Z
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.
@@ -373,6 +423,31 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
373
423
  }
374
424
  ```
375
425
 
426
+ #### `UseQueryResult`
427
+
428
+ A mounted query's state and its explicit cache and refresh actions.
429
+
430
+ ```typescript
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
442
+ /**
443
+ * Fetch this key again, even when its cached document is fresh. Observers receive the
444
+ * updated state. Resolves with that state, including an error when the request fails;
445
+ * a disabled (`null`) query resolves idle without a request.
446
+ */
447
+ refetch: () => Promise<QueryState<T>>
448
+ }
449
+ ```
450
+
376
451
  #### `IntentPrefetchProps`
377
452
 
378
453
  The handlers {@link intentPrefetchProps} returns.
@@ -464,6 +539,8 @@ lands. It is aborted only when the key changes or the component unmounts
464
539
  `useEffect` + `fetch`: an effect whose cleanup sets a `cancelled` flag, and
465
540
  whose deps include a function rebuilt each render, cancels its own request
466
541
  on every re-render and then skips the refetch.
542
+ An explicit `refetch()` is an awaited cache fetch; it can finish after the observer unmounts,
543
+ like an explicit `client.fetch(options)` caller.
467
544
 
468
545
  For a LIST, put the route's page, filter and selected view in the key and
469
546
  pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
@@ -476,13 +553,18 @@ account switch then drops the previous account's document immediately. Only
476
553
  an endpoint that answers every viewer the same takes a viewer-free key with
477
554
  `principal: 'public'`.
478
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
+
479
561
  ```typescript
480
- function useQuery<T>(options: QueryOptions<T> | null): QueryState<T>
562
+ function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
481
563
  ```
482
564
 
483
565
  - `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`.
484
566
 
485
- **Returns:** The document's state. `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.
486
568
 
487
569
  ## Injection Notes
488
570
 
@@ -548,6 +630,11 @@ Peer dependencies:
548
630
  - Prefetching respects the browser's data-saver setting and skips 2G
549
631
  connections (`shouldPrefetch()` in the core) — do not bypass that for
550
632
  "important" links; the person can still click.
633
+ - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
634
+ entry and updates every observer of that key. After a mutation whose response is not the
635
+ whole document, `await query.refetch()` reloads the displayed list. It resolves with the
636
+ resulting state (including `status: 'error'` on failure); a disabled query stays idle.
637
+ Prefer `client.set(key, response)` when the mutation already returned the whole document.
551
638
  - Errors are not thrown from the hook; read `status === 'error'` and
552
639
  `error`. `client.invalidate()` does NOT refetch a mounted page — it only
553
640
  marks documents stale, so the page keeps its error (or its old document)
@@ -556,7 +643,7 @@ Peer dependencies:
556
643
  - After a mutation, `client.set(key, response)` paints the server's own
557
644
  answer at once and supersedes an older fetch already in flight for that
558
645
  key, so its response cannot undo the mutation. An existing `fetch()` caller
559
- 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.
560
647
  `client.invalidate(prefix)` marks the affected reads stale for their next
561
648
  mount. Which key and which scope is the app's decision: the cache does not
562
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()`
@@ -295,6 +326,11 @@
295
326
  * - Prefetching respects the browser's data-saver setting and skips 2G
296
327
  * connections (`shouldPrefetch()` in the core) — do not bypass that for
297
328
  * "important" links; the person can still click.
329
+ * - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
330
+ * entry and updates every observer of that key. After a mutation whose response is not the
331
+ * whole document, `await query.refetch()` reloads the displayed list. It resolves with the
332
+ * resulting state (including `status: 'error'` on failure); a disabled query stays idle.
333
+ * Prefer `client.set(key, response)` when the mutation already returned the whole document.
298
334
  * - Errors are not thrown from the hook; read `status === 'error'` and
299
335
  * `error`. `client.invalidate()` does NOT refetch a mounted page — it only
300
336
  * marks documents stale, so the page keeps its error (or its old document)
@@ -303,7 +339,7 @@
303
339
  * - After a mutation, `client.set(key, response)` paints the server's own
304
340
  * answer at once and supersedes an older fetch already in flight for that
305
341
  * key, so its response cannot undo the mutation. An existing `fetch()` caller
306
- * 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.
307
343
  * `client.invalidate(prefix)` marks the affected reads stale for their next
308
344
  * mount. Which key and which scope is the app's decision: the cache does not
309
345
  * infer it from auth or form state.
@@ -311,6 +347,7 @@
311
347
  * @module
312
348
  */
313
349
  export * from './resource.js';
350
+ export * from './types.js';
314
351
  export * from './usePrefetch.js';
315
352
  export * from './useQuery.js';
316
353
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuTG;AAEH,cAAc,eAAe,CAAA;AAC7B,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()`
@@ -295,6 +326,11 @@
295
326
  * - Prefetching respects the browser's data-saver setting and skips 2G
296
327
  * connections (`shouldPrefetch()` in the core) — do not bypass that for
297
328
  * "important" links; the person can still click.
329
+ * - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
330
+ * entry and updates every observer of that key. After a mutation whose response is not the
331
+ * whole document, `await query.refetch()` reloads the displayed list. It resolves with the
332
+ * resulting state (including `status: 'error'` on failure); a disabled query stays idle.
333
+ * Prefer `client.set(key, response)` when the mutation already returned the whole document.
298
334
  * - Errors are not thrown from the hook; read `status === 'error'` and
299
335
  * `error`. `client.invalidate()` does NOT refetch a mounted page — it only
300
336
  * marks documents stale, so the page keeps its error (or its old document)
@@ -303,7 +339,7 @@
303
339
  * - After a mutation, `client.set(key, response)` paints the server's own
304
340
  * answer at once and supersedes an older fetch already in flight for that
305
341
  * key, so its response cannot undo the mutation. An existing `fetch()` caller
306
- * 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.
307
343
  * `client.invalidate(prefix)` marks the affected reads stale for their next
308
344
  * mount. Which key and which scope is the app's decision: the cache does not
309
345
  * infer it from auth or form state.
@@ -311,5 +347,6 @@
311
347
  * @module
312
348
  */
313
349
  export * from './resource.js';
350
+ export * from './types.js';
314
351
  export * from './usePrefetch.js';
315
352
  export * from './useQuery.js';
@@ -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,CAAA;CACd;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,8EAA8E;IAC9E,GAAG,CACD,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,GACnE,OAAO,CAAC,gBAAgB,CAAC,CAAA;IAC5B,yBAAyB;IACzB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;IAC7D,0BAA0B;IAC1B,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAA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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
  : {
@@ -0,0 +1,25 @@
1
+ /**
2
+ * React query observer contracts.
3
+ * @module
4
+ */
5
+ import type { QueryState } from '@molecule/app-query';
6
+ /** A mounted query's state and its explicit cache and refresh actions. */
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;
18
+ /**
19
+ * Fetch this key again, even when its cached document is fresh. Observers receive the
20
+ * updated state. Resolves with that state, including an error when the request fails;
21
+ * a disabled (`null`) query resolves idle without a request.
22
+ */
23
+ refetch: () => Promise<QueryState<T>>;
24
+ }
25
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +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,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"}
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import type { QueryOptions, QueryState } from '@molecule/app-query';
6
+ import type { QueryOptions } from '@molecule/app-query';
7
+ import type { UseQueryResult } from './types.js';
7
8
  /**
8
9
  * The document for `options.key`, kept current: cached data is returned on
9
10
  * the very first render (so a warmed page never flashes a loading state),
@@ -20,6 +21,8 @@ import type { QueryOptions, QueryState } from '@molecule/app-query';
20
21
  * `useEffect` + `fetch`: an effect whose cleanup sets a `cancelled` flag, and
21
22
  * whose deps include a function rebuilt each render, cancels its own request
22
23
  * on every re-render and then skips the refetch.
24
+ * An explicit `refetch()` is an awaited cache fetch; it can finish after the observer unmounts,
25
+ * like an explicit `client.fetch(options)` caller.
23
26
  *
24
27
  * For a LIST, put the route's page, filter and selected view in the key and
25
28
  * pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
@@ -32,13 +35,18 @@ import type { QueryOptions, QueryState } from '@molecule/app-query';
32
35
  * an endpoint that answers every viewer the same takes a viewer-free key with
33
36
  * `principal: 'public'`.
34
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
+ *
35
43
  * @param options - Key, fetch, freshness, and optionally `principal` with
36
44
  * `keepPreviousData`; or `null`.
37
- * @returns The document's state. `isPreviousData` is `true` while `data` is
45
+ * @returns The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is
38
46
  * the previous key's document for the same principal.
39
47
  * @throws {Error} When `keepPreviousData` is set without `principal` — the
40
48
  * hook cannot tell a route change from a principal switch, so it refuses
41
49
  * rather than risk showing one principal's document to another.
42
50
  */
43
- export declare function useQuery<T>(options: QueryOptions<T> | null): QueryState<T>;
51
+ export declare function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>;
44
52
  //# sourceMappingURL=useQuery.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAwBnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC,CA0E1E"}
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
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import { useEffect, useMemo, useRef, useState } from 'react';
6
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
7
7
  import { getQueryClient, hashQueryKey } from '@molecule/app-query';
8
8
  const IDLE = {
9
9
  data: undefined,
@@ -28,6 +28,8 @@ const IDLE = {
28
28
  * `useEffect` + `fetch`: an effect whose cleanup sets a `cancelled` flag, and
29
29
  * whose deps include a function rebuilt each render, cancels its own request
30
30
  * on every re-render and then skips the refetch.
31
+ * An explicit `refetch()` is an awaited cache fetch; it can finish after the observer unmounts,
32
+ * like an explicit `client.fetch(options)` caller.
31
33
  *
32
34
  * For a LIST, put the route's page, filter and selected view in the key and
33
35
  * pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
@@ -40,9 +42,14 @@ const IDLE = {
40
42
  * an endpoint that answers every viewer the same takes a viewer-free key with
41
43
  * `principal: 'public'`.
42
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
+ *
43
50
  * @param options - Key, fetch, freshness, and optionally `principal` with
44
51
  * `keepPreviousData`; or `null`.
45
- * @returns The document's state. `isPreviousData` is `true` while `data` is
52
+ * @returns The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is
46
53
  * the previous key's document for the same principal.
47
54
  * @throws {Error} When `keepPreviousData` is set without `principal` — the
48
55
  * hook cannot tell a route change from a principal switch, so it refuses
@@ -58,6 +65,30 @@ export function useQuery(options) {
58
65
  // Options are read once per key: a fresh `fetch` closure every render must
59
66
  // not resubscribe.
60
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]);
78
+ const refetch = useCallback(async () => {
79
+ if (!stable)
80
+ return IDLE;
81
+ const client = getQueryClient();
82
+ client.invalidate(stable.key);
83
+ try {
84
+ await client.fetch(stable);
85
+ }
86
+ catch (_error) {
87
+ // The cache publishes the failure to every observer. Return that state just as the
88
+ // initial subscription does, so an event handler can safely use `void query.refetch()`.
89
+ }
90
+ return client.getState(stable.key);
91
+ }, [stable]);
61
92
  const [state, setState] = useState(() => ({
62
93
  hash,
63
94
  value: stable ? getQueryClient().getState(stable.key) : IDLE,
@@ -114,5 +145,5 @@ export function useQuery(options) {
114
145
  const client = getQueryClient();
115
146
  return client.subscribe(stable, (value) => setState({ hash, value }));
116
147
  }, [stable, hash]);
117
- return value;
148
+ return useMemo(() => ({ ...value, setData, refetch }), [value, setData, refetch]);
118
149
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/app-query-react",
3
- "version": "1.2.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",