@molecule/app-query-solid 0.0.0-stage → 0.0.1-stage

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
@@ -1,3 +1,788 @@
1
- # Temporary Holding Version
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-11-14T15:07:26.678Z
7
+ -->
2
8
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
9
+ # @molecule/app-query-solid
10
+
11
+ Solid primitives for `@molecule/app-query`.
12
+
13
+ **Load page data with {@link useQuery}, not `fetch` inside a `createEffect`.** A hand-written
14
+ load effect that cancels its request on cleanup (a `cancelled` flag, or an `AbortController`)
15
+ re-runs its cleanup on EVERY re-run whenever one of its tracked dependencies is a function
16
+ created inline each run — `const [messages, setError] = useApiErrors()` returning arrow
17
+ functions is the usual source. The effect's own guard (`if (loaded === slug) return`) then
18
+ returns without refetching, so the response is discarded whenever it arrives after a
19
+ re-run: always on a remote server, never on localhost, which is why the page passes locally
20
+ and fails on the live URL. `useQuery` subscribes once per key, keeps its request stable
21
+ across updates, and aborts it only when the key changes or the page unmounts.
22
+
23
+ {@link useQuery} observes one document from the app's shared cache and
24
+ returns cached data on the first read; {@link usePrefetch} and
25
+ {@link intentPrefetchProps} warm a document when a person is about to
26
+ open it. Together they make a detail page open with no loading state.
27
+
28
+ This package needs a bonded client: install `@molecule/app-query` with a bond
29
+ (`@molecule/app-query-memory`, or `@molecule/app-query-tanstack`) and call the bond's
30
+ `setProvider(provider)` once at startup (the scaffold's `app/src/bonds/` does this).
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
+ signal 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
+
39
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
40
+ > It is written to be read by coding agents as much as by people, and is generated from this
41
+ > package's source — edit `src/index.ts` JSDoc, not this file.
42
+
43
+ ## Quick Start
44
+
45
+ ```tsx
46
+ import { Match, Show, Switch } from 'solid-js'
47
+ import { getClient, isHttpError } from '@molecule/app-http'
48
+ import { t } from '@molecule/app-i18n'
49
+ import { intentPrefetchProps, useQuery } from '@molecule/app-query-solid'
50
+
51
+ interface PackageDocument {
52
+ name: string
53
+ description: string
54
+ }
55
+
56
+ const packageQuery = (name: string) => ({
57
+ key: ['package', name],
58
+ fetch: async (signal: AbortSignal): Promise<PackageDocument | null> => {
59
+ try {
60
+ const response = await getClient().get<PackageDocument | null>(
61
+ `/data/packages/${encodeURIComponent(name)}.json`,
62
+ { signal },
63
+ )
64
+ return response.data
65
+ } catch (error) {
66
+ if (isHttpError(error) && error.status === 404) return null
67
+ throw error
68
+ }
69
+ },
70
+ })
71
+
72
+ function PackageLink(props: { name: string }) {
73
+ return (
74
+ <a href={`/packages/${props.name}`} {...intentPrefetchProps(packageQuery(props.name))}>
75
+ {props.name}
76
+ </a>
77
+ )
78
+ }
79
+
80
+ function PackagePage(props: { name: string }) {
81
+ // The options are an accessor, so a changed name (route param, input) re-keys
82
+ // the observer on the same mounted component, the way React re-renders useQuery.
83
+ const query = useQuery(() => packageQuery(props.name))
84
+ const loaded = (): PackageDocument | null => {
85
+ if (query.status === 'error') return null
86
+ if (query.status === 'idle' || query.status === 'loading') return null
87
+ if (query.data === undefined || query.data === null) return null
88
+ return query.data
89
+ }
90
+ return (
91
+ <Switch>
92
+ <Match when={query.status === 'error'}>
93
+ <p role="alert">
94
+ {t('packages.loadFailed', undefined, { defaultValue: 'Unable to load package.' })}
95
+ </p>
96
+ </Match>
97
+ <Match when={query.status === 'idle' || query.status === 'loading'}>
98
+ <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
99
+ </Match>
100
+ <Match when={query.data === undefined || query.data === null}>
101
+ <p>{t('packages.notFound', undefined, { defaultValue: 'Package not found.' })}</p>
102
+ </Match>
103
+ <Match when={loaded()} keyed>
104
+ {(doc) => (
105
+ <article>
106
+ <h1>{doc.name}</h1>
107
+ <p>{doc.description}</p>
108
+ </article>
109
+ )}
110
+ </Match>
111
+ </Switch>
112
+ )
113
+ }
114
+ ```
115
+
116
+ A list whose page and filter live in the URL: derive the key from the route and pass
117
+ `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
118
+ until the next page answers. The app's HTTP client sends the session, so the viewer is part of
119
+ what the answer depends on: key on it and pass the same value as `principal` — an account
120
+ switch then drops the previous account's rows at once. Pass `null` while the session is still
121
+ being restored (`status === 'loading'`; the HTTP client holds the request until then anyway),
122
+ so restoring a session never swaps a key that already rendered rows.
123
+
124
+ ```tsx
125
+ import { For, Show } from 'solid-js'
126
+ import { unwrapList } from '@molecule/app-http'
127
+ import { useAuth, useHttpClient, useListRoute, useTranslation } from '@molecule/app-solid'
128
+ import { useQuery } from '@molecule/app-query-solid'
129
+
130
+ interface Invoice {
131
+ id: string
132
+ number: string
133
+ }
134
+
135
+ function InvoiceList() {
136
+ const http = useHttpClient()
137
+ const { t } = useTranslation()
138
+ const { status, user } = useAuth<{ id: string }>()
139
+ const list = useListRoute({ pageSize: 20, filters: { status: {} } })
140
+ const viewer = (): string => (user() ? String(user().id) : 'anonymous')
141
+ const query = useQuery(() =>
142
+ status() === 'loading' || !list.canLoad
143
+ ? null
144
+ : {
145
+ key: ['invoices', viewer(), list.filters, list.page],
146
+ principal: viewer(),
147
+ keepPreviousData: true,
148
+ fetch: async (signal: AbortSignal) =>
149
+ unwrapList<Invoice>(
150
+ await http.get('/api/invoices', {
151
+ signal,
152
+ params: { ...list.filters, limit: list.pageSize, offset: list.offset },
153
+ }),
154
+ ),
155
+ },
156
+ )
157
+
158
+ // Status renders outside the item list (it is not an item), and the empty state
159
+ // describes only the key on screen, never a retained previous page.
160
+ return (
161
+ <section>
162
+ <Show when={query.isFetching || status() === 'loading'}>
163
+ <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
164
+ </Show>
165
+ <Show when={query.status === 'error'}>
166
+ <p role="alert">
167
+ {t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}
168
+ </p>
169
+ </Show>
170
+ <ul>
171
+ <For each={query.data ?? []}>
172
+ {(invoice) => (
173
+ <li>
174
+ <a href={`/invoices/${invoice.id}`}>{invoice.number}</a>
175
+ </li>
176
+ )}
177
+ </For>
178
+ </ul>
179
+ <Show when={!query.isPreviousData && query.data?.length === 0}>
180
+ <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
181
+ </Show>
182
+ <a href={list.href({ page: list.page + 1 })}>
183
+ {t('common.next', undefined, { defaultValue: 'Next page' })}
184
+ </a>
185
+ </section>
186
+ )
187
+ }
188
+ ```
189
+
190
+ A mutation or a failed load has to change a page that is ALREADY mounted, and
191
+ the cache never starts that request by itself: `set()` paints a mutation's own
192
+ response, `invalidate()` marks what it affects for the next mount, and an
193
+ explicit `fetch()` retries into the mounted page.
194
+
195
+ ```tsx
196
+ import { getClient } from '@molecule/app-http'
197
+ import { t } from '@molecule/app-i18n'
198
+ import { getQueryClient } from '@molecule/app-query'
199
+
200
+ // The key names what the document actually depends on — here the signed-in
201
+ // principal, the filter and the page. Another principal's feed is a
202
+ // different document, so an invalidation scoped to this one leaves it alone.
203
+ const feedKey = (principal: string, filter: string, page: number) =>
204
+ ['feed', principal, filter, page] as const
205
+
206
+ const feedOptions = (principal: string, filter: string, page: number) => ({
207
+ key: feedKey(principal, filter, page),
208
+ fetch: async (signal: AbortSignal) =>
209
+ (await getClient().get(`/api/feeds/${filter}`, { signal, params: { page } })).data,
210
+ })
211
+
212
+ async function setFollowing(principal: string, authorId: string, follow: boolean) {
213
+ const client = getQueryClient()
214
+ const http = getClient()
215
+ const { data: body } = follow
216
+ ? await http.post<{ feed: unknown }>(`/api/follows/${authorId}`)
217
+ : await http.delete<{ feed: unknown }>(`/api/follows/${authorId}`)
218
+ // The response IS the document: paint it now, with no second round trip.
219
+ // (If it were only a count or a flag, skip set() and invalidate() instead.)
220
+ client.set(feedKey(principal, 'following', 1), body.feed)
221
+ // Future reads of every feed this principal owns are stale.
222
+ client.invalidate(['feed', principal])
223
+ }
224
+
225
+ function Retry(props: { principal: string }) {
226
+ return (
227
+ <button
228
+ onClick={() => {
229
+ // invalidate() alone would leave the mounted page on its error;
230
+ // an explicit fetch retries into it. useQuery shows the outcome.
231
+ void getQueryClient()
232
+ .fetch(feedOptions(props.principal, 'following', 1))
233
+ // The mounted useQuery observer presents this failure via status/error.
234
+ .catch((_error) => {})
235
+ }}
236
+ >
237
+ {t('common.retry', undefined, { defaultValue: 'Retry' })}
238
+ </button>
239
+ )
240
+ }
241
+ ```
242
+
243
+ One API resource described once, for every page that reads or changes it.
244
+ `createQueryResource` returns the list and detail reads as `useQuery` options and the writes
245
+ as functions that put the server's record into the cache and fetch the lists on screen again,
246
+ so a page never mirrors a response into a local signal. A flag the API models as a sub-path
247
+ (`POST /invoices/:id/flag`, `DELETE` to clear it) is `toggle`, which resolves with the saved
248
+ record and is the `commit` of `useOptimisticValue`.
249
+
250
+ ```tsx
251
+ import { getClient, unwrapList, unwrapSingle } from '@molecule/app-http'
252
+ import { useAuth, useOptimisticValue, useTranslation } from '@molecule/app-solid'
253
+ import { createQueryResource, QueryContent, useQuery } from '@molecule/app-query-solid'
254
+
255
+ interface Invoice {
256
+ id: string
257
+ number: string
258
+ flagged: boolean
259
+ }
260
+
261
+ export const invoices = createQueryResource<Invoice>({
262
+ name: 'invoices',
263
+ path: '/invoices',
264
+ http: getClient,
265
+ readList: (response) => unwrapList<Invoice>(response),
266
+ readOne: (response) => unwrapSingle<Invoice>(response),
267
+ })
268
+
269
+ function InvoicePage(props: { id: string }) {
270
+ const { user } = useAuth<{ id: string }>()
271
+ const { t } = useTranslation()
272
+ const viewer = (): string => {
273
+ const current = user()
274
+ return current ? String(current.id) : 'anonymous'
275
+ }
276
+ const query = useQuery(() => invoices.detail(viewer(), props.id))
277
+ return (
278
+ <QueryContent
279
+ query={query}
280
+ pending={<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>}
281
+ missing={
282
+ <p role="alert">
283
+ {t('invoice.missing', undefined, { defaultValue: 'Invoice not found.' })}
284
+ </p>
285
+ }
286
+ error={() => (
287
+ <p role="alert">
288
+ {t('invoice.failed', undefined, { defaultValue: 'Unable to load invoice.' })}
289
+ </p>
290
+ )}
291
+ >
292
+ {(invoice) => <FlagButton invoice={invoice} viewer={viewer()} />}
293
+ </QueryContent>
294
+ )
295
+ }
296
+
297
+ function FlagButton(props: { invoice: Invoice; viewer: string }) {
298
+ const { t } = useTranslation()
299
+ const flag = useOptimisticValue({
300
+ value: props.invoice.flagged,
301
+ commit: async (on) =>
302
+ (await invoices.toggle(props.viewer, props.invoice.id, 'flag', on)).flagged,
303
+ })
304
+ return (
305
+ <button type="button" aria-pressed={flag.value()} onClick={() => flag.update((on) => !on)}>
306
+ {flag.value()
307
+ ? t('invoice.unflag', undefined, { defaultValue: 'Unflag' })
308
+ : t('invoice.flag', undefined, { defaultValue: 'Flag' })}{' '}
309
+ {props.invoice.number}
310
+ </button>
311
+ )
312
+ }
313
+ ```
314
+
315
+ A pager needs the whole response, including its total. Keep that read on the same resource
316
+ as its mutations, including alternate list paths; a separate hand-written `QueryOptions`
317
+ is outside the resource's refresh tracking.
318
+
319
+ ```typescript
320
+ import { getClient } from '@molecule/app-http'
321
+ import { createQueryResource } from '@molecule/app-query-solid'
322
+
323
+ interface TicketPage {
324
+ tickets: { id: string; subject: string }[]
325
+ total: number
326
+ }
327
+ const tickets = createQueryResource<TicketPage['tickets'][number]>({
328
+ name: 'tickets',
329
+ path: '/tickets',
330
+ http: getClient,
331
+ readOne: (response) => response.data as TicketPage['tickets'][number],
332
+ })
333
+ const page = tickets.listPage(
334
+ 'agent-1',
335
+ { limit: 10, offset: 20 },
336
+ (response) => response.data as TicketPage,
337
+ )
338
+ // useQuery(page) observes both rows and total. tickets.create/update/remove/toggle
339
+ // and tickets.refresh('agent-1') refresh this page too.
340
+ // A second list can use tickets.listPage(viewer, params, readPage, '/tickets/open').
341
+ // Use one canonical page reader per path; list() still returns only its own rows.
342
+ // For immediate deletion from an opaque page, add a fifth argument:
343
+ // (page, id) => {
344
+ // const rows = page.tickets.filter((row) => String(row.id) !== id)
345
+ // return { ...page, tickets: rows, total: page.total - (page.tickets.length - rows.length) }
346
+ // }
347
+ ```
348
+
349
+ A resource mutation also waits out a pre-mutation list request before fetching again;
350
+ joining that older in-flight read alone would leave the new record absent.
351
+ Successful deletion removes a row immediately, including one just created through the
352
+ resource. Stale reads cannot restore acknowledged deletions for that viewer; an explicit
353
+ successful create can recreate the identity. Opaque listPage envelopes need their own
354
+ removeFromPage adapter; no row or total property is guessed.
355
+
356
+ ## Type
357
+
358
+ `feature`
359
+
360
+ ## Installation
361
+
362
+ ```bash
363
+ npm install @molecule/app-query-solid @molecule/app-query solid-js
364
+ ```
365
+
366
+ ## API
367
+
368
+ ### Interfaces
369
+
370
+ #### `ResourceResponse`
371
+
372
+ The part of an HTTP response a resource reads.
373
+
374
+ ```typescript
375
+ interface ResourceResponse {
376
+ /** The parsed response body. */
377
+ data: unknown
378
+ }
379
+ ```
380
+
381
+ #### `ResourceHttp`
382
+
383
+ The HTTP client a resource calls: the app's own bonded client (`getClient()` from
384
+ `@molecule/app-http`) has this shape. Only what a resource uses is named here.
385
+
386
+ ```typescript
387
+ interface ResourceHttp {
388
+ /** Reads `path`; `signal` cancels it and `params` become the query string. */
389
+ get(
390
+ path: string,
391
+ options?: { signal?: AbortSignal; params?: Record<string, unknown> },
392
+ ): Promise<ResourceResponse>
393
+ /** Creates at `path`. */
394
+ post(path: string, body?: unknown): Promise<ResourceResponse>
395
+ /** Replaces at `path`. */
396
+ put(path: string, body?: unknown): Promise<ResourceResponse>
397
+ /** Changes part of the record at `path`. */
398
+ patch(path: string, body?: unknown): Promise<ResourceResponse>
399
+ /** Removes at `path`. */
400
+ delete(path: string): Promise<ResourceResponse>
401
+ }
402
+ ```
403
+
404
+ #### `QueryResourceConfig`
405
+
406
+ What {@link createQueryResource} needs to know about one resource.
407
+
408
+ ```typescript
409
+ interface QueryResourceConfig<T> {
410
+ /** The first element of every cache key of this resource, e.g. `'invoices'`. */
411
+ name: string
412
+ /** The collection's path under the API base, e.g. `'/invoices'`. */
413
+ path: string
414
+ /** The app's HTTP client, read on every call so a client bonded later is the one used. */
415
+ http: () => ResourceHttp
416
+ /** The field a record is addressed by in a URL. Defaults to `'id'`. */
417
+ id?: keyof T & string
418
+ /** The HTTP method the API updates a record with. Defaults to `'put'`. */
419
+ updateMethod?: 'put' | 'patch'
420
+ /** Reads the records out of a list response. Defaults to the body itself. */
421
+ readList?: (response: ResourceResponse) => T[]
422
+ /** Reads the record out of a detail or write response. Defaults to the body itself. */
423
+ readOne?: (response: ResourceResponse) => T | null
424
+ }
425
+ ```
426
+
427
+ #### `QueryResource`
428
+
429
+ The reads and writes {@link createQueryResource} returns.
430
+
431
+ ```typescript
432
+ interface QueryResource<T, Create = Partial<T>, Update = Partial<T>> {
433
+ /**
434
+ * `useQuery` options for the collection. `viewer` is who the answer is for (the signed-in id,
435
+ * or `'anonymous'`); a page or filter change keeps the rows on screen until the next answer.
436
+ */
437
+ list(viewer: string, params?: Record<string, unknown>): QueryOptions<T[]>
438
+ /**
439
+ * Options for a collection's whole page (rows plus totals), or a filtered collection path.
440
+ * Reads share this resource's mutation refresh and viewer isolation. `readPage` reads the
441
+ * canonical page response for `path`; row-only `list` reads keep a separate cache entry.
442
+ * Supply `removeFromPage` for opaque page envelopes to remove acknowledged deletions
443
+ * immediately and keep stale list responses from restoring them.
444
+ */
445
+ listPage<Page>(
446
+ viewer: string,
447
+ params: Record<string, unknown>,
448
+ readPage: (response: ResourceResponse) => Page,
449
+ path?: string,
450
+ removeFromPage?: (page: Page, id: string) => Page,
451
+ ): QueryOptions<Page>
452
+ /**
453
+ * `useQuery` options for one record, or null while `id` is not known yet (`useQuery(null)`
454
+ * observes nothing). A missing record resolves to null, not to an error.
455
+ */
456
+ detail(viewer: string, id: string | null | undefined): QueryOptions<T | null> | null
457
+ /** Creates a record, shows it in the cache and refreshes the lists on screen. */
458
+ create(viewer: string, input: Create): Promise<T>
459
+ /** Updates a record, shows the saved record in the cache and refreshes the lists on screen. */
460
+ update(viewer: string, id: string, input: Update): Promise<T>
461
+ /** Removes a record from detail and tracked row lists, then refreshes those lists. */
462
+ remove(viewer: string, id: string): Promise<void>
463
+ /**
464
+ * Switches a flag the API models as a sub-path: `POST path/id/action` turns it on and
465
+ * `DELETE path/id/action` turns it off. Resolves with the saved record, so it is the `commit`
466
+ * of `useOptimisticValue`.
467
+ * The saved detail is published before tracked lists finish refreshing; this promise waits
468
+ * for those refreshes. Render the shared controller's value and let it queue inverse clicks
469
+ * during that interval. A page-local busy guard can drop a click on the newly changed label.
470
+ */
471
+ toggle(viewer: string, id: string, action: string, on: boolean): Promise<T>
472
+ /** Fetches the lists on screen again, after a change this resource did not make itself. */
473
+ refresh(viewer: string): Promise<void>
474
+ }
475
+ ```
476
+
477
+ #### `UseQueryResult`
478
+
479
+ A mounted query's state and its explicit cache and refresh actions. The state
480
+ fields read as plain values at read time (each reads the observer's current
481
+ state), so a JSX binding that reads them re-renders when the document
482
+ changes, and a test can snapshot the object at any moment.
483
+
484
+ ```typescript
485
+ interface UseQueryResult<T> extends QueryState<T> {
486
+ /**
487
+ * Publish a saved document to this key and all its observers. Render `data`
488
+ * directly instead of copying it to local state: later cache updates then
489
+ * remain visible. A function receives this key's current cached document,
490
+ * never retained previous-page data. Returning `undefined` leaves the cache
491
+ * unchanged. A disabled (`null`) query does nothing, including not calling an
492
+ * updater. Like React state setters, wrap a function-valued document in an
493
+ * updater. A saved callback stays bound to its original key. The write
494
+ * supersedes older in-flight reads, using the bonded client's `set` contract.
495
+ */
496
+ setData: (value: T | ((previous: T | undefined) => T | undefined)) => void
497
+ /**
498
+ * Fetch this key again, even when its cached document is fresh. Observers
499
+ * receive the updated state. Resolves with that state, including an error
500
+ * when the request fails; a disabled (`null`) query resolves idle without a
501
+ * request.
502
+ */
503
+ refetch: () => Promise<QueryState<T>>
504
+ }
505
+ ```
506
+
507
+ #### `QueryContentProps`
508
+
509
+ A loaded document owns its controls; absent documents expose only status content.
510
+
511
+ ```typescript
512
+ interface QueryContentProps<T> {
513
+ /** State from useQuery, or any compatible query observer. */
514
+ query: Pick<QueryState<T>, 'data' | 'status' | 'error'>
515
+ /** Mounted only with a real document, including false, zero and an empty list. */
516
+ children: (data: NonNullable<T>) => JSX.Element
517
+ /** Initial idle/loading content. Render a status node, never a fake item or action. */
518
+ pending?: JSX.Element
519
+ /** Content for a loaded null record. Null is distinct from an unfinished request. */
520
+ missing?: JSX.Element
521
+ /** A failed initial read. Cached data stays visible if its refresh fails. */
522
+ error?: (error: unknown) => JSX.Element
523
+ }
524
+ ```
525
+
526
+ #### `IntentPrefetchProps`
527
+
528
+ The handlers {@link intentPrefetchProps} returns.
529
+
530
+ ```typescript
531
+ interface IntentPrefetchProps {
532
+ onPointerEnter: () => void
533
+ onFocus: () => void
534
+ onTouchStart: () => void
535
+ }
536
+ ```
537
+
538
+ ### Functions
539
+
540
+ #### `prefetchQuery(options)`
541
+
542
+ Warms the cache for a document, when the connection can afford it (see
543
+ `shouldPrefetch()` in the core). Safe to call repeatedly: a fresh or
544
+ in-flight document is skipped, and failures are swallowed.
545
+
546
+ ```typescript
547
+ function prefetchQuery<T>(options: QueryOptions<T>): void
548
+ ```
549
+
550
+ - `options` — Key, fetch, freshness.
551
+
552
+ #### `createQueryResource(config)`
553
+
554
+ Describe one API resource once and get its reads and writes on the shared cache.
555
+
556
+ A page that loads with `fetch` inside an effect and mirrors the answer into `useState` has to
557
+ re-solve the same problems on every screen: a late answer for the previous page lands
558
+ over the current one, and a list still shows what it showed before a comment was added.
559
+ Here the reads are `useQuery` options (one key per
560
+ viewer, page and filter; the previous rows stay until the next answer) and every write puts
561
+ the server's own record into the cache and fetches the lists on screen again.
562
+
563
+ The factory supplies data operations. Mount a keyed
564
+ control inside `QueryContent` (your framework's query package: `@molecule/app-query-react`,
565
+ `-vue`, …) so it receives a loaded record and stays mounted during refresh.
566
+ For a server-backed toggle, use `useOptimisticValue` from your framework binding
567
+ (`@molecule/app-react`, `@molecule/app-vue`, …), or `OptimisticToggleButton` from its UI
568
+ package (`@molecule/app-ui-react`, …) for a boolean. Pass `toggle` as its
569
+ commit adapter, return the saved flag/count, and render the controller's value for the action
570
+ label too. Do not block clicks while that commit is pending. The resource example in
571
+ `@molecule/app-query-react` composes these APIs; a custom handler must provide the same
572
+ readiness and ordering itself.
573
+
574
+ Markup, labels and routes stay in the app. The factory has no vendor in it: the HTTP client
575
+ and the query provider are whatever the app bonded.
576
+
577
+ ```typescript
578
+ function createQueryResource<T, Create = Partial<T>, Update = Partial<T>>(
579
+ config: QueryResourceConfig<T>,
580
+ ): QueryResource<T, Create, Update>
581
+ ```
582
+
583
+ - `config` — The resource's name, path, HTTP client and response readers.
584
+
585
+ **Returns:** List and detail query options, and create, update, remove, toggle and refresh.
586
+
587
+ #### `QueryContent(props)`
588
+
589
+ The loaded-data branch receives a non-null document. Pending, failed initial reads and
590
+ missing records never mount that branch, so its actions cannot swallow an early click.
591
+ Cached data remains mounted during refresh, including a failed refresh. Status fallbacks
592
+ belong outside the list or record container rendered by `children`, and so does a refresh
593
+ line; the default fallbacks render nothing.
594
+
595
+ ```typescript
596
+ function QueryContent<T>(props: QueryContentProps<T>): JSX.Element
597
+ ```
598
+
599
+ - `props` — Query state, loaded content and optional status fallbacks.
600
+
601
+ **Returns:** Loaded content or the appropriate fallback, switching as the state changes.
602
+
603
+ #### `usePrefetch()`
604
+
605
+ A stable `prefetch(options)` function for event handlers.
606
+
607
+ ```typescript
608
+ function usePrefetch(): <T>(options: QueryOptions<T>) => void
609
+ ```
610
+
611
+ **Returns:** The prefetch function.
612
+
613
+ #### `intentPrefetchProps(options)`
614
+
615
+ Event handlers that warm a document at the first sign of intent: the
616
+ pointer arriving, keyboard focus, or a touch starting. Spread them onto a
617
+ link: `<a {...intentPrefetchProps(packageQuery(name))} />`.
618
+
619
+ ```typescript
620
+ function intentPrefetchProps<T>(options: QueryOptions<T>): IntentPrefetchProps
621
+ ```
622
+
623
+ - `options` — Key, fetch, freshness.
624
+
625
+ **Returns:** The handlers.
626
+
627
+ #### `useQuery(options)`
628
+
629
+ The document for the options' key, kept current: cached data is read on the
630
+ very first render (so a warmed page never flashes a loading state), a stale
631
+ or missing document is fetched, and every change re-renders what reads the
632
+ result. Pass `null` to observe nothing. A key change resets to that key's
633
+ state; the hook never hands a caller another key's document — unless the
634
+ caller opts into {@link QueryOptions.keepPreviousData}, and then only within
635
+ one {@link QueryOptions.principal}.
636
+
637
+ The request is stable across re-renders — a parent state change neither
638
+ restarts it nor cancels it, so a response that arrives after one still
639
+ lands. It is aborted only when the key changes or the component unmounts
640
+ (the `signal` given to `options.fetch`). Use this instead of a hand-written
641
+ `createEffect` + `fetch`: an effect whose `onCleanup` sets a `cancelled`
642
+ flag, and whose tracked dependencies include a function rebuilt each run,
643
+ cancels its own request on every run and then skips the refetch.
644
+ An explicit `refetch()` is an awaited cache fetch; it can finish after the
645
+ observer unmounts, like an explicit `client.fetch(options)` caller.
646
+
647
+ A component body runs once in Solid, so pass the options as an accessor when
648
+ any part of them can change (`() => packageQuery(props.name)`): a changed
649
+ key — or principal, or `keepPreviousData` flag — is then followed on the SAME
650
+ mounted hook, the way React re-renders `useQuery` with a new options object.
651
+
652
+ For a LIST, put the route's page, filter and selected view in the key and
653
+ pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
654
+ then keeps the rows already on screen until the new page answers, instead of
655
+ rendering a loading state over an empty list. The key names everything the
656
+ answer depends on, and the app's HTTP client sends the session, so a list the
657
+ server can filter or personalize per viewer puts the viewer in its key and
658
+ passes the same value as `principal` (`'anonymous'` when signed out): an
659
+ account switch then drops the previous account's document immediately. Only
660
+ an endpoint that answers every viewer the same takes a viewer-free key with
661
+ `principal: 'public'`.
662
+
663
+ For custom mutation handlers, `setData(saved)` publishes the server's response to this
664
+ key and every observer. Use `setData(current => next)` for a local cache update. Render
665
+ `data` directly; a component-local copy stops observing later server responses. Prefer
666
+ `createQueryResource` when the API's reads and writes can share one resource definition.
667
+ Mount record-dependent actions inside `QueryContent` (or an explicit non-null data branch),
668
+ so a visible action cannot return early because its initial record is still missing.
669
+ Keep loaded actions mounted during refreshes. Server-backed toggles use `useOptimisticValue`
670
+ from `@molecule/app-solid` or `OptimisticToggleButton` from `@molecule/app-ui-solid` to keep
671
+ their displayed label and queued clicks on the same state while a save finishes.
672
+
673
+ ```typescript
674
+ function useQuery<T>(options: QueryOptionsSource<T>): UseQueryResult<T>
675
+ ```
676
+
677
+ - `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`; or an accessor of either (the options a component recomputes from its props — every change is followed on the same instance).
678
+
679
+ **Returns:** The document's state, `setData()` and `refetch()`. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
680
+
681
+ ## Injection Notes
682
+
683
+ ### Requirements
684
+
685
+ Peer dependencies:
686
+
687
+ - `@molecule/app-query` ^1.2.0
688
+ - `solid-js` ^1.8.0
689
+
690
+ ### Runtime Dependencies
691
+
692
+ - `@molecule/app-query`
693
+ - `solid-js`
694
+
695
+ - **`useQuery` reads the cache synchronously on the first render.** A
696
+ document prefetched from a hovered link, or seeded with `client.set()`
697
+ from a server-rendered JSON island, renders at once — no spinner, no
698
+ layout shift. Render loading from `status === 'idle' || status === 'loading'`;
699
+ `undefined` data can also accompany a completed error. A completed `null`
700
+ response is missing, not pending. The detail example treats only HTTP 404
701
+ or a successful null response as missing; other errors stay load failures.
702
+ The app's bonded HTTP client rejects non-2xx responses. Native `fetch`
703
+ resolves them, so a custom fetcher must check `response.ok` before JSON.
704
+ - **A component body runs once in Solid: pass the options as an accessor.**
705
+ `useQuery(() => packageQuery(props.name))` follows a changed name (route
706
+ param, input, parent state) on the same mounted hook, the way React
707
+ re-renders `useQuery` with a new options object. Options built once from
708
+ props are read once — a later prop change would not re-key the observer.
709
+ - **Mount a detail region and its actions only after its initial document arrives.**
710
+ A visible container is not a loaded document: a caller may wait for that container and
711
+ read its text once, or click its button, while `data` is still undefined. Put the loading
712
+ message outside the detail region, as in `PackagePage` above. Keep record-dependent
713
+ controls absent or natively disabled until the record exists; returning early inside
714
+ an enabled click handler loses that click. `client.set()` protects a cache mutation
715
+ from an older read, but cannot recover a click whose handler never sent the mutation.
716
+ - **The key is the identity.** Building `options` inside the accessor is
717
+ fine; the hook resubscribes only when the key's value changes, not when
718
+ the `fetch` closure does.
719
+ - **A key change normally resets to the new key's state.** For a list's own
720
+ page/filter/view change, opt into `keepPreviousData` with a `principal`;
721
+ `isPreviousData` tells you the rows on screen belong to the key you just
722
+ left. A completed response (including an empty list) replaces them, and a
723
+ changed principal drops them, so an account switch never shows the previous
724
+ account's rows. Do not emulate this with a local signal mirror of the
725
+ query data — that mirror is what serves stale rows under a new page, or
726
+ blanks the list on an update.
727
+ - **The key names the viewer whenever the answer can depend on it.** The
728
+ app's HTTP client sends the session, so the server may filter or
729
+ personalize even a list that guests can see (a `favorited` or `following`
730
+ flag), and the cache serves a key's document to whoever observes it,
731
+ across sign-in and sign-out. Key such a list on the viewer
732
+ (`user() ? String(user().id) : 'anonymous'`), pass the same value as
733
+ `principal`, and pass `null` while the session is still being restored
734
+ (`status === 'loading'`; the HTTP client holds the request until then
735
+ anyway), so restoring a session never swaps a key that already rendered
736
+ rows. A viewer-free key with `principal: 'public'` is only for an endpoint
737
+ that answers every viewer the same. A protected `useListRoute` view also
738
+ passes `null` while `canLoad` is false.
739
+ - **Render loading, empty and error status outside the item list**, and never
740
+ give a placeholder the item's own class or element shape: a list read by
741
+ the item class (or by `:first-child`) must contain only real items. An
742
+ empty array is a loaded empty state, not a missing response; render it
743
+ only when `isPreviousData` is not set, because a retained document belongs
744
+ to the key you just left.
745
+ - `intentPrefetchProps` spreads three handlers onto a link. It is a plain
746
+ function (not a primitive), so it works inside `<For>` too.
747
+ - Prefetching respects the browser's data-saver setting and skips 2G
748
+ connections (`shouldPrefetch()` in the core) — do not bypass that for
749
+ "important" links; the person can still click.
750
+ - **Refresh a mounted document with `query.refetch()`.** It fetches even a fresh cache
751
+ entry and updates every observer of that key. After a mutation whose response is not the
752
+ whole document, `await query.refetch()` reloads the displayed list. It resolves with the
753
+ resulting state (including `status: 'error'` on failure); a disabled query stays idle.
754
+ Prefer `client.set(key, response)` when the mutation already returned the whole document.
755
+ - Errors are not thrown from the hook; read `status === 'error'` and
756
+ `error`. `client.invalidate()` does NOT refetch a mounted page — it only
757
+ marks documents stale, so the page keeps its error (or its old document)
758
+ until the app retries with `client.fetch(options)` or the page subscribes
759
+ again (a key change or a re-mount).
760
+ - After a mutation, `client.set(key, response)` paints the server's own
761
+ answer at once and supersedes an older fetch already in flight for that
762
+ key, so its response cannot undo the mutation. An existing `fetch()` caller
763
+ still settles independently of the cache write; read `client.get(key)` for the newest document.
764
+ `client.invalidate(prefix)` marks the affected reads stale for their next
765
+ mount. Which key and which scope is the app's decision: the cache does not
766
+ infer it from auth or form state.
767
+
768
+ Render resource-dependent lists and controls through {@link QueryContent}. Its child function
769
+ receives only loaded, non-null data; loading and error content never mount item actions.
770
+ It renders cached content during refresh and treats an empty list, false and zero as data.
771
+ Put the list, or the record's own container (its card, header or profile block), inside the
772
+ child and every status line (loading, error, `isFetching` refresh) beside it, never inside it:
773
+ a reader that finds the container and reads its paragraph must read the record, not "Loading…".
774
+
775
+ ```tsx
776
+ <QueryContent
777
+ query={query}
778
+ pending={<p role="status">{loadingLabel}</p>}
779
+ missing={<p>{missingLabel}</p>}
780
+ error={() => <p role="alert">{errorLabel}</p>}
781
+ >
782
+ {(record) => <RecordActions record={record} />}
783
+ </QueryContent>
784
+ ```
785
+
786
+ Keep every resource identity in the query key. A boundary cannot correct a query that supplies
787
+ another record's cached data. For a list, map real rows inside the child; never style a status
788
+ placeholder as a row. QueryContent is headless and owns no translations or styling.