@molecule/app-query-react 1.3.0 → 1.5.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-13T01:18:38.398Z
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,47 @@ 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
+ // For immediate deletion from an opaque page, add a fifth argument:
306
+ // (page, id) => {
307
+ // const rows = page.tickets.filter((row) => String(row.id) !== id)
308
+ // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
309
+ // }
310
+ ```
311
+
312
+ A resource mutation also waits out a pre-mutation list request before fetching again;
313
+ joining that older in-flight read alone would leave the new record absent.
314
+ Successful deletion removes a row immediately, including one just created through the
315
+ resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
316
+ successful create can recreate the identity. Opaque listPage envelopes need their own
317
+ removeFromPage adapter; no row or total property is guessed.
318
+
271
319
  ## Type
272
320
 
273
321
  `feature`
@@ -351,6 +399,20 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
351
399
  * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
352
400
  */
353
401
  list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
402
+ /**
403
+ * Options for a collection's whole page (rows plus totals), or a filtered collection path.
404
+ * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
405
+ * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
406
+ * Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
407
+ * immediately and keep stale list responses from restoring them.
408
+ */
409
+ listPage<Page>(
410
+ viewer: string,
411
+ params: Record<string, unknown>,
412
+ readPage: (response: ResourceResponse) => Page,
413
+ path?: string,
414
+ removeFromPage?: (page: Page, id: string) => Page,
415
+ ): QueryOptions<Page>
354
416
  /**
355
417
  * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
356
418
  * observes nothing). A missing record resolves to null, not to an error.
@@ -360,7 +422,7 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
360
422
  create(viewer: string, input: Create): Promise<T>
361
423
  /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
362
424
  update(viewer: string, id: string, input: Update): Promise<T>
363
- /** Removes a record, drops it from the cache and refreshes the lists on screen. */
425
+ /** Removes a record from detail and tracked row lists, then refreshes those lists. */
364
426
  remove(viewer: string, id: string): Promise<void>
365
427
  /**
366
428
  * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
@@ -375,10 +437,20 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
375
437
 
376
438
  #### `UseQueryResult`
377
439
 
378
- A mounted query's state and its explicit refresh action.
440
+ A mounted query's state and its explicit cache and refresh actions.
379
441
 
380
442
  ```typescript
381
443
  interface UseQueryResult<T> extends QueryState<T> {
444
+ /**
445
+ * Publish a saved document to this key and all its observers. Render `data` directly
446
+ * instead of copying it to local state: later cache updates then remain visible.
447
+ * A function receives this key's current cached document, never retained previous-page
448
+ * data. Returning `undefined` leaves the cache unchanged. A disabled (`null`) query
449
+ * does nothing, including not calling an updater. Like React state setters, wrap a
450
+ * function-valued document in an updater. A saved callback stays bound to its original key.
451
+ * The write supersedes older in-flight reads, using the bonded client's `set` contract.
452
+ */
453
+ setData: (value: T | ((previous: T | undefined) => T | undefined)) => void
382
454
  /**
383
455
  * Fetch this key again, even when its cached document is fresh. Observers receive the
384
456
  * updated state. Resolves with that state, including an error when the request fails;
@@ -493,13 +565,18 @@ account switch then drops the previous account's document immediately. Only
493
565
  an endpoint that answers every viewer the same takes a viewer-free key with
494
566
  `principal: 'public'`.
495
567
 
568
+ For custom mutation handlers, `setData(saved)` publishes the server's response to this
569
+ key and every observer. Use `setData(current => next)` for a local cache update. Render
570
+ `data` directly; a component-local copy stops observing later server responses. Prefer
571
+ `createQueryResource` when the API's reads and writes can share one resource definition.
572
+
496
573
  ```typescript
497
574
  function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
498
575
  ```
499
576
 
500
577
  - `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`.
501
578
 
502
- **Returns:** The document's state and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
579
+ **Returns:** The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
503
580
 
504
581
  ## Injection Notes
505
582
 
@@ -578,7 +655,7 @@ Peer dependencies:
578
655
  - After a mutation, `client.set(key, response)` paints the server's own
579
656
  answer at once and supersedes an older fetch already in flight for that
580
657
  key, so its response cannot undo the mutation. An existing `fetch()` caller
581
- still settles with its older response or a bond-specific cancellation.
658
+ still settles independently of the cache write; read `client.get(key)` for the newest document.
582
659
  `client.invalidate(prefix)` marks the affected reads stale for their next
583
660
  mount. Which key and which scope is the app's decision: the cache does not
584
661
  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,39 @@
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
+ * // For immediate deletion from an opaque page, add a fifth argument:
275
+ * // (page, id) => {
276
+ * // const rows = page.tickets.filter((row) => String(row.id) !== id)
277
+ * // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
278
+ * // }
279
+ * ```
280
+ * A resource mutation also waits out a pre-mutation list request before fetching again;
281
+ * joining that older in-flight read alone would leave the new record absent.
282
+ * Successful deletion removes a row immediately, including one just created through the
283
+ * resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
284
+ * successful create can recreate the identity. Opaque listPage envelopes need their own
285
+ * removeFromPage adapter; no row or total property is guessed.
286
+ *
247
287
  * @remarks
248
288
  * - **`useQuery` reads the cache synchronously on the first render.** A
249
289
  * document prefetched from a hovered link, or seeded with `client.set()`
@@ -308,7 +348,7 @@
308
348
  * - After a mutation, `client.set(key, response)` paints the server's own
309
349
  * answer at once and supersedes an older fetch already in flight for that
310
350
  * key, so its response cannot undo the mutation. An existing `fetch()` caller
311
- * still settles with its older response or a bond-specific cancellation.
351
+ * still settles independently of the cache write; read `client.get(key)` for the newest document.
312
352
  * `client.invalidate(prefix)` marks the affected reads stale for their next
313
353
  * mount. Which key and which scope is the app's decision: the cache does not
314
354
  * 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoWG;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,39 @@
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
+ * // For immediate deletion from an opaque page, add a fifth argument:
275
+ * // (page, id) => {
276
+ * // const rows = page.tickets.filter((row) => String(row.id) !== id)
277
+ * // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
278
+ * // }
279
+ * ```
280
+ * A resource mutation also waits out a pre-mutation list request before fetching again;
281
+ * joining that older in-flight read alone would leave the new record absent.
282
+ * Successful deletion removes a row immediately, including one just created through the
283
+ * resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
284
+ * successful create can recreate the identity. Opaque listPage envelopes need their own
285
+ * removeFromPage adapter; no row or total property is guessed.
286
+ *
247
287
  * @remarks
248
288
  * - **`useQuery` reads the cache synchronously on the first render.** A
249
289
  * document prefetched from a hovered link, or seeded with `client.set()`
@@ -308,7 +348,7 @@
308
348
  * - After a mutation, `client.set(key, response)` paints the server's own
309
349
  * answer at once and supersedes an older fetch already in flight for that
310
350
  * key, so its response cannot undo the mutation. An existing `fetch()` caller
311
- * still settles with its older response or a bond-specific cancellation.
351
+ * still settles independently of the cache write; read `client.get(key)` for the newest document.
312
352
  * `client.invalidate(prefix)` marks the affected reads stale for their next
313
353
  * mount. Which key and which scope is the app's decision: the cache does not
314
354
  * infer it from auth or form state.
@@ -53,6 +53,14 @@ 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
+ * Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
61
+ * immediately and keep stale list responses from restoring them.
62
+ */
63
+ listPage<Page>(viewer: string, params: Record<string, unknown>, readPage: (response: ResourceResponse) => Page, path?: string, removeFromPage?: (page: Page, id: string) => Page): QueryOptions<Page>;
56
64
  /**
57
65
  * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
58
66
  * observes nothing). A missing record resolves to null, not to an error.
@@ -62,7 +70,7 @@ export interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
62
70
  create(viewer: string, input: Create): Promise<T>;
63
71
  /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
64
72
  update(viewer: string, id: string, input: Update): Promise<T>;
65
- /** Removes a record, drops it from the cache and refreshes the lists on screen. */
73
+ /** Removes a record from detail and tracked row lists, then refreshes those lists. */
66
74
  remove(viewer: string, id: string): Promise<void>;
67
75
  /**
68
76
  * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
@@ -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,EAAE,OAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;IAC5D,4CAA4C;IAC5C,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;IAC9D,yBAAyB;IACzB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,C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AAC,EAAE,MAAM,EAAE,MAAM,CAAC,CA8JlC"}
package/dist/resource.js CHANGED
@@ -34,50 +34,96 @@ 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 removed = new Map();
38
+ const removals = (viewer) => removed.get(viewer) ?? new Set();
39
+ const recordId = (record) => {
40
+ const id = record != null ? record[idField] : undefined;
41
+ return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined;
42
+ };
43
+ const withoutRemoved = (viewer, rows) => {
44
+ const ids = removed.get(viewer);
45
+ return ids?.size ? rows.filter((record) => !ids.has(recordId(record) ?? '')) : rows;
46
+ };
47
+ const projectPage = (viewer, page, remove) => {
48
+ if (!remove)
49
+ return page;
50
+ for (const id of removals(viewer))
51
+ page = remove(page, id);
52
+ return page;
53
+ };
54
+ const track = (viewer, options, remove) => {
55
+ const hash = hashQueryKey(options.key);
56
+ recent.delete(hash);
57
+ recent.set(hash, {
58
+ viewer,
59
+ options,
60
+ ...(remove ? { remove: (page, id) => remove(page, id) } : {}),
61
+ });
62
+ for (const stale of [...recent.keys()].slice(0, -REFRESHED_LISTS))
63
+ recent.delete(stale);
64
+ return options;
65
+ };
37
66
  const list = (viewer, params = {}) => {
38
67
  const options = {
39
68
  key: [config.name, viewer, 'list', params],
40
69
  principal: viewer,
41
70
  keepPreviousData: true,
42
- fetch: async (signal) => readList(await config.http().get(base, { signal, params })),
71
+ fetch: async (signal) => withoutRemoved(viewer, readList(await config.http().get(base, { signal, params }))),
43
72
  };
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;
73
+ return track(viewer, options, (rows) => withoutRemoved(viewer, rows));
50
74
  };
51
75
  const refresh = async (viewer) => {
52
76
  const client = getQueryClient();
53
77
  client.invalidate([config.name, viewer, 'list']);
54
78
  await Promise.all([...recent.values()]
55
79
  .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
- })));
80
+ .map(async (entry) => {
81
+ // fetch() deduplicates an existing request. It may have read before this write,
82
+ // so joining it alone cannot refresh the list after the mutation.
83
+ const pending = client.getState(entry.options.key).isFetching;
84
+ const fetch = () => client.fetch(entry.options).catch((_error) => {
85
+ // The mounted query presents its own failure; the mutation already succeeded.
86
+ });
87
+ await fetch();
88
+ if (pending) {
89
+ client.invalidate(entry.options.key);
90
+ await fetch();
91
+ }
92
+ }));
60
93
  };
61
- const saved = async (viewer, response) => {
94
+ const saved = async (viewer, response, created = false) => {
62
95
  const record = readOne(response);
63
96
  if (record == null)
64
97
  throw new Error(`${config.name}: the response held no record`);
65
- const id = record[idField];
66
- if (typeof id === 'string' || typeof id === 'number')
67
- getQueryClient().set(detailKey(viewer, String(id)), record);
98
+ const id = recordId(record);
99
+ if (id !== undefined) {
100
+ if (created)
101
+ removed.get(viewer)?.delete(id);
102
+ if (!removals(viewer).has(id))
103
+ getQueryClient().set(detailKey(viewer, id), record);
104
+ }
68
105
  await refresh(viewer);
69
106
  return record;
70
107
  };
71
108
  return {
72
109
  list,
110
+ listPage: (viewer, params, readPage, path = base, removeFromPage) => track(viewer, {
111
+ key: [config.name, viewer, 'list', 'page', path, params],
112
+ principal: viewer,
113
+ keepPreviousData: true,
114
+ fetch: async (signal) => projectPage(viewer, readPage(await config.http().get(path, { signal, params })), removeFromPage),
115
+ }, removeFromPage),
73
116
  detail: (viewer, id) => id == null || id === ''
74
117
  ? null
75
118
  : {
76
119
  key: detailKey(viewer, id),
77
120
  principal: viewer,
78
121
  fetch: async (signal) => {
122
+ if (removals(viewer).has(id))
123
+ return null;
79
124
  try {
80
- return readOne(await config.http().get(one(id), { signal }));
125
+ const record = readOne(await config.http().get(one(id), { signal }));
126
+ return removals(viewer).has(id) ? null : record;
81
127
  }
82
128
  catch (error) {
83
129
  // A record that does not exist is an answer, not a failed load.
@@ -87,11 +133,22 @@ export function createQueryResource(config) {
87
133
  }
88
134
  },
89
135
  },
90
- create: async (viewer, input) => saved(viewer, await config.http().post(base, input)),
136
+ create: async (viewer, input) => saved(viewer, await config.http().post(base, input), true),
91
137
  update: async (viewer, id, input) => saved(viewer, await config.http()[config.updateMethod ?? 'put'](one(id), input)),
92
138
  remove: async (viewer, id) => {
93
139
  await config.http().delete(one(id));
94
- getQueryClient().set(detailKey(viewer, id), null);
140
+ const ids = removed.get(viewer) ?? new Set();
141
+ ids.add(id);
142
+ removed.set(viewer, ids);
143
+ const client = getQueryClient();
144
+ client.set(detailKey(viewer, id), null);
145
+ for (const entry of recent.values()) {
146
+ if (entry.viewer !== viewer || !entry.remove)
147
+ continue;
148
+ const page = client.getState(entry.options.key).data;
149
+ if (page !== undefined)
150
+ client.set(entry.options.key, entry.remove(page, id));
151
+ }
95
152
  await refresh(viewer);
96
153
  },
97
154
  toggle: async (viewer, id, action, on) => {
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.5.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",