@molecule/app-query-react 1.5.0 → 1.6.1

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-13T01:18:38.398Z
6
+ Generated: 2026-11-14T12:29:21.947Z
7
7
  -->
8
8
 
9
9
  # @molecule/app-query-react
@@ -236,8 +236,8 @@ record and is the `commit` of `useOptimisticValue`.
236
236
 
237
237
  ```tsx
238
238
  import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
239
- import { createQueryResource, useQuery } from '@molecule/app-query-react'
240
- import { useAuth, useOptimisticValue } from '@molecule/app-react'
239
+ import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
240
+ import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
241
241
 
242
242
  interface Invoice {
243
243
  id: string
@@ -255,20 +255,40 @@ export const invoices = createQueryResource<Invoice>({
255
255
 
256
256
  function InvoicePage({ id }: { id: string }) {
257
257
  const { user } = useAuth<{ id: string }>()
258
+ const { t } = useTranslation()
258
259
  const viewer = user ? String(user.id) : 'anonymous'
259
- const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
260
- if (status === 'idle' || status === 'loading') return <p role=status>…</p>
261
- if (!invoice) return <p role=alert>…</p>
262
- return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
260
+ const query = useQuery(invoices.detail(viewer, id))
261
+ return (
262
+ <QueryContent
263
+ query={query}
264
+ pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
265
+ missing={
266
+ <p role="alert">
267
+ {t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}
268
+ </p>
269
+ }
270
+ error={() => (
271
+ <p role="alert">
272
+ {t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}
273
+ </p>
274
+ )}
275
+ >
276
+ {(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
277
+ </QueryContent>
278
+ )
263
279
  }
264
280
 
265
281
  function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
282
+ const { t } = useTranslation()
266
283
  const flag = useOptimisticValue({
267
284
  value: invoice.flagged,
268
285
  commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
269
286
  })
270
287
  return (
271
- <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
288
+ <button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
289
+ {flag.value
290
+ ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
291
+ : t('invoice.flag', undefined, { defaultValue: 'Flag' })}{' '}
272
292
  {invoice.number}
273
293
  </button>
274
294
  )
@@ -428,6 +448,9 @@ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
428
448
  * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
429
449
  * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
430
450
  * of `useOptimisticValue`.
451
+ * The saved detail is published before tracked lists finish refreshing; this promise waits
452
+ * for those refreshes. Render the shared controller's value and let it queue inverse clicks
453
+ * during that interval. A page-local busy guard can drop a click on the newly changed label.
431
454
  */
432
455
  toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
433
456
  /** Fetches the lists on screen again, after a change this resource did not make itself. */
@@ -460,6 +483,25 @@ interface UseQueryResult<T> extends QueryState<T> {
460
483
  }
461
484
  ```
462
485
 
486
+ #### `QueryContentProps`
487
+
488
+ A loaded document owns its controls; absent documents expose only status content.
489
+
490
+ ```typescript
491
+ interface QueryContentProps<T> {
492
+ /** State from useQuery, or any compatible query observer. */
493
+ query: Pick<QueryState<T>, 'data' | 'status' | 'error'>
494
+ /** Mounted only with a real document, including false, zero and an empty list. */
495
+ children: (data: NonNullable<T>) => ReactNode
496
+ /** Initial idle/loading content. Render a status node, never a fake item or action. */
497
+ pending?: ReactNode
498
+ /** Content for a loaded null record. Null is distinct from an unfinished request. */
499
+ missing?: ReactNode
500
+ /** A failed initial read. Cached data stays visible if its refresh fails. */
501
+ error?: (error: unknown) => ReactNode
502
+ }
503
+ ```
504
+
463
505
  #### `IntentPrefetchProps`
464
506
 
465
507
  The handlers {@link intentPrefetchProps} returns.
@@ -474,17 +516,40 @@ interface IntentPrefetchProps {
474
516
 
475
517
  ### Functions
476
518
 
519
+ #### `prefetchQuery(options)`
520
+
521
+ Warms the cache for a document, when the connection can afford it (see
522
+ `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
523
+ in-flight document is skipped, and failures are swallowed.
524
+
525
+ ```typescript
526
+ function prefetchQuery<T>(options: QueryOptions<T>): void
527
+ ```
528
+
529
+ - `options` — Key, fetch, freshness.
530
+
477
531
  #### `createQueryResource(config)`
478
532
 
479
533
  Describe one API resource once and get its reads and writes on the shared cache.
480
534
 
481
535
  A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
482
- re-solve the same three problems on every screen: a late answer for the previous page lands
483
- over the current one, a list still shows what it showed before a comment was added, and a
484
- button is live before its record exists. Here the reads are `useQuery` options (one key per
536
+ re-solve the same problems on every screen: a late answer for the previous page lands
537
+ over the current one, and a list still shows what it showed before a comment was added.
538
+ Here the reads are `useQuery` options (one key per
485
539
  viewer, page and filter; the previous rows stay until the next answer) and every write puts
486
540
  the server's own record into the cache and fetches the lists on screen again.
487
541
 
542
+ The factory supplies data operations. Mount a keyed
543
+ control inside `QueryContent` (your framework's query package: `@molecule/app-query-react`,
544
+ `-vue`, …) so it receives a loaded record and stays mounted during refresh.
545
+ For a server-backed toggle, use `useOptimisticValue` from your framework binding
546
+ (`@molecule/app-react`, `@molecule/app-vue`, …), or `OptimisticToggleButton` from its UI
547
+ package (`@molecule/app-ui-react`, …) for a boolean. Pass `toggle` as its
548
+ commit adapter, return the saved flag/count, and render the controller's value for the action
549
+ label too. Do not block clicks while that commit is pending. The resource example in
550
+ `@molecule/app-query-react` composes these APIs; a custom handler must provide the same
551
+ readiness and ordering itself.
552
+
488
553
  Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
489
554
  and the query provider are whatever the app bonded.
490
555
 
@@ -498,17 +563,27 @@ function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
498
563
 
499
564
  **Returns:** List and detail query options, and create, update, remove, toggle and refresh.
500
565
 
501
- #### `prefetchQuery(options)`
566
+ #### `QueryContent(props)`
502
567
 
503
- Warms the cache for a document, when the connection can afford it (see
504
- `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
505
- in-flight document is skipped, and failures are swallowed.
568
+ The loaded-data branch receives a non-null document. Pending, failed initial reads and
569
+ missing records never mount that branch, so its actions cannot swallow an early click.
570
+ Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
571
+ belong outside the list or record container rendered by `children`, and so does a refresh
572
+ line; the default fallbacks render nothing.
506
573
 
507
574
  ```typescript
508
- function prefetchQuery<T>(options: QueryOptions<T>): void
575
+ function QueryContent<T>({
576
+ query,
577
+ children,
578
+ pending = null,
579
+ missing = null,
580
+ error,
581
+ }: QueryContentProps<T>): ReactNode
509
582
  ```
510
583
 
511
- - `options` — Key, fetch, freshness.
584
+ - `props` — Query state, loaded content and optional status fallbacks.
585
+
586
+ **Returns:** Loaded content or the appropriate fallback.
512
587
 
513
588
  #### `usePrefetch()`
514
589
 
@@ -569,6 +644,11 @@ For custom mutation handlers, `setData(saved)` publishes the server's response t
569
644
  key and every observer. Use `setData(current => next)` for a local cache update. Render
570
645
  `data` directly; a component-local copy stops observing later server responses. Prefer
571
646
  `createQueryResource` when the API's reads and writes can share one resource definition.
647
+ Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
648
+ so a visible action cannot return early because its initial record is still missing.
649
+ Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
650
+ from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
651
+ their displayed label and queued clicks on the same state while a save finishes.
572
652
 
573
653
  ```typescript
574
654
  function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
@@ -584,7 +664,7 @@ function useQuery<T>(options: QueryOptions<T> | null): UseQueryResult<T>
584
664
 
585
665
  Peer dependencies:
586
666
 
587
- - `@molecule/app-query` ^1.1.0
667
+ - `@molecule/app-query` ^1.2.0
588
668
  - `react` ^18.0.0 || ^19.0.0
589
669
 
590
670
  ### Runtime Dependencies
@@ -659,3 +739,25 @@ Peer dependencies:
659
739
  `client.invalidate(prefix)` marks the affected reads stale for their next
660
740
  mount. Which key and which scope is the app's decision: the cache does not
661
741
  infer it from auth or form state.
742
+
743
+ Render resource-dependent lists and controls through {@link QueryContent}. Its child function
744
+ receives only loaded, non-null data; loading and error content never mount item actions.
745
+ It renders cached content during refresh and treats an empty list, false and zero as data.
746
+ Put the list, or the record's own container (its card, header or profile block), inside the
747
+ child and every status line (loading, error, `isFetching` refresh) beside it, never inside it:
748
+ a reader that finds the container and reads its paragraph must read the record, not "Loading…".
749
+
750
+ ```tsx
751
+ <QueryContent
752
+ query={query}
753
+ pending={<p role="status">{loadingLabel}</p>}
754
+ missing={<p>{missingLabel}</p>}
755
+ error={() => <p role="alert">{errorLabel}</p>}
756
+ >
757
+ {(record) => <RecordActions record={record} />}
758
+ </QueryContent>
759
+ ```
760
+
761
+ Keep every resource identity in the query key. A boundary cannot correct a query that supplies
762
+ another record's cached data. For a list, map real rows inside the child; never style a status
763
+ placeholder as a row. QueryContent is headless and owns no translations or styling.
package/dist/index.d.ts CHANGED
@@ -212,8 +212,8 @@
212
212
  *
213
213
  * ```tsx
214
214
  * import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
215
- * import { createQueryResource, useQuery } from '@molecule/app-query-react'
216
- * import { useAuth, useOptimisticValue } from '@molecule/app-react'
215
+ * import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
216
+ * import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
217
217
  *
218
218
  * interface Invoice {
219
219
  * id: string
@@ -231,21 +231,32 @@
231
231
  *
232
232
  * function InvoicePage({ id }: { id: string }) {
233
233
  * const { user } = useAuth<{ id: string }>()
234
+ * const { t } = useTranslation()
234
235
  * const viewer = user ? String(user.id) : 'anonymous'
235
- * const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
236
- * if (status === 'idle' || status === 'loading') return <p role=status>…</p>
237
- * if (!invoice) return <p role=alert>…</p>
238
- * return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
236
+ * const query = useQuery(invoices.detail(viewer, id))
237
+ * return (
238
+ * <QueryContent
239
+ * query={query}
240
+ * pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
241
+ * missing={<p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>}
242
+ * error={() => <p role="alert">{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}</p>}
243
+ * >
244
+ * {(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
245
+ * </QueryContent>
246
+ * )
239
247
  * }
240
248
  *
241
249
  * function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
250
+ * const { t } = useTranslation()
242
251
  * const flag = useOptimisticValue({
243
252
  * value: invoice.flagged,
244
253
  * commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
245
254
  * })
246
255
  * return (
247
- * <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
248
- * {invoice.number}
256
+ * <button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
257
+ * {flag.value
258
+ * ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
259
+ * : t('invoice.flag', undefined, { defaultValue: 'Flag' })} {invoice.number}
249
260
  * </button>
250
261
  * )
251
262
  * }
@@ -353,8 +364,27 @@
353
364
  * mount. Which key and which scope is the app's decision: the cache does not
354
365
  * infer it from auth or form state.
355
366
  *
367
+ * Render resource-dependent lists and controls through {@link QueryContent}. Its child function
368
+ * receives only loaded, non-null data; loading and error content never mount item actions.
369
+ * It renders cached content during refresh and treats an empty list, false and zero as data.
370
+ * Put the list, or the record's own container (its card, header or profile block), inside the
371
+ * child and every status line (loading, error, `isFetching` refresh) beside it, never inside it:
372
+ * a reader that finds the container and reads its paragraph must read the record, not "Loading…".
373
+ *
374
+ * ```tsx
375
+ * <QueryContent query={query} pending={<p role="status">{loadingLabel}</p>}
376
+ * missing={<p>{missingLabel}</p>} error={() => <p role="alert">{errorLabel}</p>}>
377
+ * {(record) => <RecordActions record={record} />}
378
+ * </QueryContent>
379
+ * ```
380
+ *
381
+ * Keep every resource identity in the query key. A boundary cannot correct a query that supplies
382
+ * another record's cached data. For a list, map real rows inside the child; never style a status
383
+ * placeholder as a row. QueryContent is headless and owns no translations or styling.
384
+ *
356
385
  * @module
357
386
  */
387
+ export * from './query-content.js';
358
388
  export * from './resource.js';
359
389
  export * from './types.js';
360
390
  export * from './usePrefetch.js';
@@ -1 +1 @@
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"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiYG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
package/dist/index.js CHANGED
@@ -212,8 +212,8 @@
212
212
  *
213
213
  * ```tsx
214
214
  * import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
215
- * import { createQueryResource, useQuery } from '@molecule/app-query-react'
216
- * import { useAuth, useOptimisticValue } from '@molecule/app-react'
215
+ * import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-react'
216
+ * import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-react'
217
217
  *
218
218
  * interface Invoice {
219
219
  * id: string
@@ -231,21 +231,32 @@
231
231
  *
232
232
  * function InvoicePage({ id }: { id: string }) {
233
233
  * const { user } = useAuth<{ id: string }>()
234
+ * const { t } = useTranslation()
234
235
  * const viewer = user ? String(user.id) : 'anonymous'
235
- * const { data: invoice, status } = useQuery(invoices.detail(viewer, id))
236
- * if (status === 'idle' || status === 'loading') return <p role=status>…</p>
237
- * if (!invoice) return <p role=alert>…</p>
238
- * return <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />
236
+ * const query = useQuery(invoices.detail(viewer, id))
237
+ * return (
238
+ * <QueryContent
239
+ * query={query}
240
+ * pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
241
+ * missing={<p role="alert">{t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}</p>}
242
+ * error={() => <p role="alert">{t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}</p>}
243
+ * >
244
+ * {(invoice) => <FlagButton key={invoice.id} invoice={invoice} viewer={viewer} />}
245
+ * </QueryContent>
246
+ * )
239
247
  * }
240
248
  *
241
249
  * function FlagButton({ invoice, viewer }: { invoice: Invoice; viewer: string }) {
250
+ * const { t } = useTranslation()
242
251
  * const flag = useOptimisticValue({
243
252
  * value: invoice.flagged,
244
253
  * commit: async (on) => (await invoices.toggle(viewer, invoice.id, 'flag', on)).flagged,
245
254
  * })
246
255
  * return (
247
- * <button type=button aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
248
- * {invoice.number}
256
+ * <button type="button" aria-pressed={flag.value} onClick={() => flag.update((on) => !on)}>
257
+ * {flag.value
258
+ * ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
259
+ * : t('invoice.flag', undefined, { defaultValue: 'Flag' })} {invoice.number}
249
260
  * </button>
250
261
  * )
251
262
  * }
@@ -353,8 +364,27 @@
353
364
  * mount. Which key and which scope is the app's decision: the cache does not
354
365
  * infer it from auth or form state.
355
366
  *
367
+ * Render resource-dependent lists and controls through {@link QueryContent}. Its child function
368
+ * receives only loaded, non-null data; loading and error content never mount item actions.
369
+ * It renders cached content during refresh and treats an empty list, false and zero as data.
370
+ * Put the list, or the record's own container (its card, header or profile block), inside the
371
+ * child and every status line (loading, error, `isFetching` refresh) beside it, never inside it:
372
+ * a reader that finds the container and reads its paragraph must read the record, not "Loading…".
373
+ *
374
+ * ```tsx
375
+ * <QueryContent query={query} pending={<p role="status">{loadingLabel}</p>}
376
+ * missing={<p>{missingLabel}</p>} error={() => <p role="alert">{errorLabel}</p>}>
377
+ * {(record) => <RecordActions record={record} />}
378
+ * </QueryContent>
379
+ * ```
380
+ *
381
+ * Keep every resource identity in the query key. A boundary cannot correct a query that supplies
382
+ * another record's cached data. For a list, map real rows inside the child; never style a status
383
+ * placeholder as a row. QueryContent is headless and owns no translations or styling.
384
+ *
356
385
  * @module
357
386
  */
387
+ export * from './query-content.js';
358
388
  export * from './resource.js';
359
389
  export * from './types.js';
360
390
  export * from './usePrefetch.js';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Render resource-dependent content only after its document exists.
3
+ * @module
4
+ */
5
+ import type { ReactNode } from 'react';
6
+ import type { QueryContentProps } from './types.js';
7
+ /**
8
+ * The loaded-data branch receives a non-null document. Pending, failed initial reads and
9
+ * missing records never mount that branch, so its actions cannot swallow an early click.
10
+ * Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
11
+ * belong outside the list or record container rendered by `children`, and so does a refresh
12
+ * line; the default fallbacks render nothing.
13
+ *
14
+ * @param props - Query state, loaded content and optional status fallbacks.
15
+ * @returns Loaded content or the appropriate fallback.
16
+ */
17
+ export declare function QueryContent<T>({ query, children, pending, missing, error, }: QueryContentProps<T>): ReactNode;
18
+ //# sourceMappingURL=query-content.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-content.d.ts","sourceRoot":"","sources":["../src/query-content.tsx"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAEtC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEnD;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,EAC9B,KAAK,EACL,QAAQ,EACR,OAAc,EACd,OAAc,EACd,KAAK,GACN,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,SAAS,CAMlC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The loaded-data branch receives a non-null document. Pending, failed initial reads and
3
+ * missing records never mount that branch, so its actions cannot swallow an early click.
4
+ * Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
5
+ * belong outside the list or record container rendered by `children`, and so does a refresh
6
+ * line; the default fallbacks render nothing.
7
+ *
8
+ * @param props - Query state, loaded content and optional status fallbacks.
9
+ * @returns Loaded content or the appropriate fallback.
10
+ */
11
+ export function QueryContent({ query, children, pending = null, missing = null, error, }) {
12
+ if (query.data === undefined) {
13
+ return query.status === 'error' && error ? error(query.error) : pending;
14
+ }
15
+ if (query.data === null)
16
+ return missing;
17
+ return children(query.data);
18
+ }
@@ -1,102 +1,10 @@
1
1
  /**
2
- * One API resource on the shared query cache: its list and detail reads as `useQuery` options,
3
- * and its writes as functions that put the server's answer into the cache.
2
+ * One API resource on the shared query cache. `createQueryResource` is framework-neutral, so it
3
+ * lives in `@molecule/app-query` (with its full documentation); this package re-exports it so
4
+ * React pages import it next to `useQuery` and `QueryContent`.
4
5
  *
5
6
  * @module
6
7
  */
7
- import type { QueryOptions } from '@molecule/app-query';
8
- /** The part of an HTTP response a resource reads. */
9
- export interface ResourceResponse {
10
- /** The parsed response body. */
11
- data: unknown;
12
- }
13
- /**
14
- * The HTTP client a resource calls: the app's own bonded client (`getClient()` from
15
- * `@molecule/app-http`) has this shape. Only what a resource uses is named here.
16
- */
17
- export interface ResourceHttp {
18
- /** Reads `path`; `signal` cancels it and `params` become the query string. */
19
- get(path: string, options?: {
20
- signal?: AbortSignal;
21
- params?: Record<string, unknown>;
22
- }): Promise<ResourceResponse>;
23
- /** Creates at `path`. */
24
- post(path: string, body?: unknown): Promise<ResourceResponse>;
25
- /** Replaces at `path`. */
26
- put(path: string, body?: unknown): Promise<ResourceResponse>;
27
- /** Changes part of the record at `path`. */
28
- patch(path: string, body?: unknown): Promise<ResourceResponse>;
29
- /** Removes at `path`. */
30
- delete(path: string): Promise<ResourceResponse>;
31
- }
32
- /** What {@link createQueryResource} needs to know about one resource. */
33
- export interface QueryResourceConfig<T> {
34
- /** The first element of every cache key of this resource, e.g. `'invoices'`. */
35
- name: string;
36
- /** The collection's path under the API base, e.g. `'/invoices'`. */
37
- path: string;
38
- /** The app's HTTP client, read on every call so a client bonded later is the one used. */
39
- http: () => ResourceHttp;
40
- /** The field a record is addressed by in a URL. Defaults to `'id'`. */
41
- id?: keyof T & string;
42
- /** The HTTP method the API updates a record with. Defaults to `'put'`. */
43
- updateMethod?: 'put' | 'patch';
44
- /** Reads the records out of a list response. Defaults to the body itself. */
45
- readList?: (response: ResourceResponse) => T[];
46
- /** Reads the record out of a detail or write response. Defaults to the body itself. */
47
- readOne?: (response: ResourceResponse) => T | null;
48
- }
49
- /** The reads and writes {@link createQueryResource} returns. */
50
- export interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
51
- /**
52
- * `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
53
- * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
54
- */
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>;
64
- /**
65
- * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
66
- * observes nothing). A missing record resolves to null, not to an error.
67
- */
68
- detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null;
69
- /** Creates a record, shows it in the cache and refreshes the lists on screen. */
70
- create(viewer: string, input: Create): Promise<T>;
71
- /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
72
- update(viewer: string, id: string, input: Update): Promise<T>;
73
- /** Removes a record from detail and tracked row lists, then refreshes those lists. */
74
- remove(viewer: string, id: string): Promise<void>;
75
- /**
76
- * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
77
- * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
78
- * of `useOptimisticValue`.
79
- */
80
- toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>;
81
- /** Fetches the lists on screen again, after a change this resource did not make itself. */
82
- refresh(viewer: string): Promise<void>;
83
- }
84
- /**
85
- * Describe one API resource once and get its reads and writes on the shared cache.
86
- *
87
- * A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
88
- * re-solve the same three problems on every screen: a late answer for the previous page lands
89
- * over the current one, a list still shows what it showed before a comment was added, and a
90
- * button is live before its record exists. Here the reads are `useQuery` options (one key per
91
- * viewer, page and filter; the previous rows stay until the next answer) and every write puts
92
- * the server's own record into the cache and fetches the lists on screen again.
93
- *
94
- * Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
95
- * and the query provider are whatever the app bonded.
96
- *
97
- * @param config - The resource's name, path, HTTP client and response readers.
98
- * @returns List and detail query options, and create, update, remove, toggle and refresh.
99
- * @throws {Error} When a write's response holds no record.
100
- */
101
- export declare function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(config: QueryResourceConfig<T>): QueryResource<T, Create, Update>;
8
+ export type { QueryResource, QueryResourceConfig, ResourceHttp, ResourceResponse, } from '@molecule/app-query';
9
+ export { createQueryResource } from '@molecule/app-query';
102
10
  //# sourceMappingURL=resource.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/resource.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,YAAY,EACV,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,gBAAgB,GACjB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAA"}
package/dist/resource.js CHANGED
@@ -1,160 +1,8 @@
1
1
  /**
2
- * One API resource on the shared query cache: its list and detail reads as `useQuery` options,
3
- * and its writes as functions that put the server's answer into the cache.
2
+ * One API resource on the shared query cache. `createQueryResource` is framework-neutral, so it
3
+ * lives in `@molecule/app-query` (with its full documentation); this package re-exports it so
4
+ * React pages import it next to `useQuery` and `QueryContent`.
4
5
  *
5
6
  * @module
6
7
  */
7
- import { getQueryClient, hashQueryKey } from '@molecule/app-query';
8
- /** How many of a viewer's most recent lists a write fetches again. */
9
- const REFRESHED_LISTS = 4;
10
- /**
11
- * Describe one API resource once and get its reads and writes on the shared cache.
12
- *
13
- * A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
14
- * re-solve the same three problems on every screen: a late answer for the previous page lands
15
- * over the current one, a list still shows what it showed before a comment was added, and a
16
- * button is live before its record exists. Here the reads are `useQuery` options (one key per
17
- * viewer, page and filter; the previous rows stay until the next answer) and every write puts
18
- * the server's own record into the cache and fetches the lists on screen again.
19
- *
20
- * Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
21
- * and the query provider are whatever the app bonded.
22
- *
23
- * @param config - The resource's name, path, HTTP client and response readers.
24
- * @returns List and detail query options, and create, update, remove, toggle and refresh.
25
- * @throws {Error} When a write's response holds no record.
26
- */
27
- export function createQueryResource(config) {
28
- const readList = config.readList ?? ((response) => response.data);
29
- const readOne = config.readOne ?? ((response) => response.data);
30
- const idField = config.id ?? 'id';
31
- const base = config.path.replace(/\/+$/, '');
32
- const one = (id) => `${base}/${encodeURIComponent(id)}`;
33
- const detailKey = (viewer, id) => [config.name, viewer, 'detail', id];
34
- // The lists handed out most recently, newest last: the ones a write fetches again. A list
35
- // nobody reads any more costs one request and is then dropped by the next ones.
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
- };
66
- const list = (viewer, params = {}) => {
67
- const options = {
68
- key: [config.name, viewer, 'list', params],
69
- principal: viewer,
70
- keepPreviousData: true,
71
- fetch: async (signal) => withoutRemoved(viewer, readList(await config.http().get(base, { signal, params }))),
72
- };
73
- return track(viewer, options, (rows) => withoutRemoved(viewer, rows));
74
- };
75
- const refresh = async (viewer) => {
76
- const client = getQueryClient();
77
- client.invalidate([config.name, viewer, 'list']);
78
- await Promise.all([...recent.values()]
79
- .filter((entry) => entry.viewer === viewer)
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
- }));
93
- };
94
- const saved = async (viewer, response, created = false) => {
95
- const record = readOne(response);
96
- if (record == null)
97
- throw new Error(`${config.name}: the response held no 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
- }
105
- await refresh(viewer);
106
- return record;
107
- };
108
- return {
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),
116
- detail: (viewer, id) => id == null || id === ''
117
- ? null
118
- : {
119
- key: detailKey(viewer, id),
120
- principal: viewer,
121
- fetch: async (signal) => {
122
- if (removals(viewer).has(id))
123
- return null;
124
- try {
125
- const record = readOne(await config.http().get(one(id), { signal }));
126
- return removals(viewer).has(id) ? null : record;
127
- }
128
- catch (error) {
129
- // A record that does not exist is an answer, not a failed load.
130
- if (error?.status === 404)
131
- return null;
132
- throw error;
133
- }
134
- },
135
- },
136
- create: async (viewer, input) => saved(viewer, await config.http().post(base, input), true),
137
- update: async (viewer, id, input) => saved(viewer, await config.http()[config.updateMethod ?? 'put'](one(id), input)),
138
- remove: async (viewer, id) => {
139
- await config.http().delete(one(id));
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
- }
152
- await refresh(viewer);
153
- },
154
- toggle: async (viewer, id, action, on) => {
155
- const path = `${one(id)}/${action.replace(/^\/+/, '')}`;
156
- return saved(viewer, on ? await config.http().post(path) : await config.http().delete(path));
157
- },
158
- refresh,
159
- };
160
- }
8
+ export { createQueryResource } from '@molecule/app-query';
package/dist/types.d.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  * React query observer contracts.
3
3
  * @module
4
4
  */
5
+ import type { ReactNode } from 'react';
5
6
  import type { QueryState } from '@molecule/app-query';
6
7
  /** A mounted query's state and its explicit cache and refresh actions. */
7
8
  export interface UseQueryResult<T> extends QueryState<T> {
@@ -22,4 +23,17 @@ export interface UseQueryResult<T> extends QueryState<T> {
22
23
  */
23
24
  refetch: () => Promise<QueryState<T>>;
24
25
  }
26
+ /** A loaded document owns its controls; absent documents expose only status content. */
27
+ export interface QueryContentProps<T> {
28
+ /** State from useQuery, or any compatible query observer. */
29
+ query: Pick<QueryState<T>, 'data' | 'status' | 'error'>;
30
+ /** Mounted only with a real document, including false, zero and an empty list. */
31
+ children: (data: NonNullable<T>) => ReactNode;
32
+ /** Initial idle/loading content. Render a status node, never a fake item or action. */
33
+ pending?: ReactNode;
34
+ /** Content for a loaded null record. Null is distinct from an unfinished request. */
35
+ missing?: ReactNode;
36
+ /** A failed initial read. Cached data stays visible if its refresh fails. */
37
+ error?: (error: unknown) => ReactNode;
38
+ }
25
39
  //# sourceMappingURL=types.d.ts.map
@@ -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,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"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAEtC,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;AAED,wFAAwF;AACxF,MAAM,WAAW,iBAAiB,CAAC,CAAC;IAClC,6DAA6D;IAC7D,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAC,CAAA;IACvD,kFAAkF;IAClF,QAAQ,EAAE,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,KAAK,SAAS,CAAA;IAC7C,uFAAuF;IACvF,OAAO,CAAC,EAAE,SAAS,CAAA;IACnB,qFAAqF;IACrF,OAAO,CAAC,EAAE,SAAS,CAAA;IACnB,6EAA6E;IAC7E,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,SAAS,CAAA;CACtC"}
@@ -1,17 +1,11 @@
1
1
  /**
2
- * Warm the cache ahead of a navigation.
2
+ * Warm the cache ahead of a navigation. `prefetchQuery` itself is framework-neutral and lives in
3
+ * `@molecule/app-query`; this module re-exports it and adds the React hook and link handlers.
3
4
  *
4
5
  * @module
5
6
  */
6
7
  import type { QueryOptions } from '@molecule/app-query';
7
- /**
8
- * Warms the cache for a document, when the connection can afford it (see
9
- * `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
10
- * in-flight document is skipped, and failures are swallowed.
11
- *
12
- * @param options - Key, fetch, freshness.
13
- */
14
- export declare function prefetchQuery<T>(options: QueryOptions<T>): void;
8
+ export { prefetchQuery } from '@molecule/app-query';
15
9
  /**
16
10
  * A stable `prefetch(options)` function for event handlers.
17
11
  *
@@ -1 +1 @@
1
- {"version":3,"file":"usePrefetch.d.ts","sourceRoot":"","sources":["../src/usePrefetch.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGvD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,CAG/D;AAED;;;;GAIG;AACH,wBAAgB,WAAW,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,CAEnE;AAED,wDAAwD;AACxD,MAAM,WAAW,mBAAmB;IAClC,cAAc,EAAE,MAAM,IAAI,CAAA;IAC1B,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,YAAY,EAAE,MAAM,IAAI,CAAA;CACzB;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAGpF"}
1
+ {"version":3,"file":"usePrefetch.d.ts","sourceRoot":"","sources":["../src/usePrefetch.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD;;;;GAIG;AACH,wBAAgB,WAAW,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,CAEnE;AAED,wDAAwD;AACxD,MAAM,WAAW,mBAAmB;IAClC,cAAc,EAAE,MAAM,IAAI,CAAA;IAC1B,OAAO,EAAE,MAAM,IAAI,CAAA;IACnB,YAAY,EAAE,MAAM,IAAI,CAAA;CACzB;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAGpF"}
@@ -1,22 +1,12 @@
1
1
  /**
2
- * Warm the cache ahead of a navigation.
2
+ * Warm the cache ahead of a navigation. `prefetchQuery` itself is framework-neutral and lives in
3
+ * `@molecule/app-query`; this module re-exports it and adds the React hook and link handlers.
3
4
  *
4
5
  * @module
5
6
  */
6
7
  import { useCallback } from 'react';
7
- import { getQueryClient, shouldPrefetch } from '@molecule/app-query';
8
- /**
9
- * Warms the cache for a document, when the connection can afford it (see
10
- * `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
11
- * in-flight document is skipped, and failures are swallowed.
12
- *
13
- * @param options - Key, fetch, freshness.
14
- */
15
- export function prefetchQuery(options) {
16
- if (!shouldPrefetch())
17
- return;
18
- getQueryClient().prefetch(options);
19
- }
8
+ import { prefetchQuery } from '@molecule/app-query';
9
+ export { prefetchQuery } from '@molecule/app-query';
20
10
  /**
21
11
  * A stable `prefetch(options)` function for event handlers.
22
12
  *
@@ -39,6 +39,11 @@ import type { UseQueryResult } from './types.js';
39
39
  * key and every observer. Use `setData(current => next)` for a local cache update. Render
40
40
  * `data` directly; a component-local copy stops observing later server responses. Prefer
41
41
  * `createQueryResource` when the API's reads and writes can share one resource definition.
42
+ * Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
43
+ * so a visible action cannot return early because its initial record is still missing.
44
+ * Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
45
+ * from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
46
+ * their displayed label and queued clicks on the same state while a save finishes.
42
47
  *
43
48
  * @param options - Key, fetch, freshness, and optionally `principal` with
44
49
  * `keepPreviousData`; or `null`.
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,cAAc,CAAC,CAAC,CAAC,CAkG9E"}
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;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
@@ -46,6 +46,11 @@ const IDLE = {
46
46
  * key and every observer. Use `setData(current => next)` for a local cache update. Render
47
47
  * `data` directly; a component-local copy stops observing later server responses. Prefer
48
48
  * `createQueryResource` when the API's reads and writes can share one resource definition.
49
+ * Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
50
+ * so a visible action cannot return early because its initial record is still missing.
51
+ * Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
52
+ * from `@molecule/app-react` or `OptimisticToggleButton` from `@molecule/app-ui-react` to keep
53
+ * their displayed label and queued clicks on the same state while a save finishes.
49
54
  *
50
55
  * @param options - Key, fetch, freshness, and optionally `principal` with
51
56
  * `keepPreviousData`; or `null`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/app-query-react",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
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",
@@ -36,13 +36,13 @@
36
36
  "directory": "packages/app/features/query-react"
37
37
  },
38
38
  "peerDependencies": {
39
- "@molecule/app-query": "^1.1.0",
39
+ "@molecule/app-query": "^1.2.0",
40
40
  "react": "^18.0.0 || ^19.0.0"
41
41
  },
42
42
  "devDependencies": {
43
- "@molecule/app-query": "1.1.3",
44
- "@molecule/app-query-memory": "1.0.4",
45
- "@molecule/app-query-tanstack": "1.0.4",
43
+ "@molecule/app-query": "1.2.0",
44
+ "@molecule/app-query-memory": "1.0.5",
45
+ "@molecule/app-query-tanstack": "1.0.5",
46
46
  "@types/node": "26.6.5",
47
47
  "@types/react": "19.3.0",
48
48
  "@types/react-dom": "19.3.0",