@molecule/app-query-react 1.0.4 → 1.1.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 +116 -4
- package/dist/index.d.ts +101 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +101 -0
- package/dist/useQuery.d.ts +21 -3
- package/dist/useQuery.d.ts.map +1 -1
- package/dist/useQuery.js +72 -7
- package/package.json +3 -3
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-10-
|
|
6
|
+
Generated: 2026-10-25T13:01:55.013Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/app-query-react
|
|
@@ -36,6 +36,7 @@ This package needs a bonded client: install `@molecule/app-query` with a bond
|
|
|
36
36
|
## Quick Start
|
|
37
37
|
|
|
38
38
|
```tsx
|
|
39
|
+
import { Link } from 'react-router'
|
|
39
40
|
import { intentPrefetchProps, useQuery } from '@molecule/app-query-react'
|
|
40
41
|
|
|
41
42
|
const packageQuery = (name: string) => ({
|
|
@@ -59,6 +60,79 @@ function PackagePage({ name }: { name: string }) {
|
|
|
59
60
|
}
|
|
60
61
|
```
|
|
61
62
|
|
|
63
|
+
A list whose page and filter live in the URL: derive the key from the route and pass
|
|
64
|
+
`keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
|
|
65
|
+
until the next page answers. The app's HTTP client sends the session, so the viewer is part of
|
|
66
|
+
what the answer depends on: key on it and pass the same value as `principal` — an account
|
|
67
|
+
switch then drops the previous account's rows at once. Pass `null` while the session is still
|
|
68
|
+
being restored (`status === 'loading'`; the HTTP client holds the request until then anyway),
|
|
69
|
+
so restoring a session never swaps a key that already rendered rows.
|
|
70
|
+
|
|
71
|
+
```tsx
|
|
72
|
+
import { Link } from 'react-router'
|
|
73
|
+
import { unwrapList } from '@molecule/app-http'
|
|
74
|
+
import { useQuery } from '@molecule/app-query-react'
|
|
75
|
+
import { useAuth, useHttpClient, useTranslation } from '@molecule/app-react'
|
|
76
|
+
import { useListRoute } from '@molecule/app-routing-react-router'
|
|
77
|
+
|
|
78
|
+
interface Invoice {
|
|
79
|
+
id: string
|
|
80
|
+
number: string
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function InvoiceList() {
|
|
84
|
+
const http = useHttpClient()
|
|
85
|
+
const { t } = useTranslation()
|
|
86
|
+
const { status, user } = useAuth<{ id: string }>()
|
|
87
|
+
const list = useListRoute({ pageSize: 20, filters: { status: {} } })
|
|
88
|
+
const viewer = user ? String(user.id) : 'anonymous'
|
|
89
|
+
const query = useQuery(
|
|
90
|
+
status === 'loading' || !list.canLoad
|
|
91
|
+
? null
|
|
92
|
+
: {
|
|
93
|
+
key: ['invoices', viewer, list.filters, list.page],
|
|
94
|
+
principal: viewer,
|
|
95
|
+
keepPreviousData: true,
|
|
96
|
+
fetch: async (signal: AbortSignal) =>
|
|
97
|
+
unwrapList<Invoice>(
|
|
98
|
+
await http.get('/api/invoices', {
|
|
99
|
+
signal,
|
|
100
|
+
params: { ...list.filters, limit: list.pageSize, offset: list.offset },
|
|
101
|
+
}),
|
|
102
|
+
),
|
|
103
|
+
},
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
// Status renders outside the item list (it is not an item), and the empty state
|
|
107
|
+
// describes only the key on screen, never a retained previous page.
|
|
108
|
+
return (
|
|
109
|
+
<section>
|
|
110
|
+
{status === 'loading' || query.isFetching ? (
|
|
111
|
+
<p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
|
|
112
|
+
) : null}
|
|
113
|
+
{query.status === 'error' ? (
|
|
114
|
+
<p role="alert">
|
|
115
|
+
{t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}
|
|
116
|
+
</p>
|
|
117
|
+
) : null}
|
|
118
|
+
<ul>
|
|
119
|
+
{query.data?.map((invoice) => (
|
|
120
|
+
<li key={invoice.id}>
|
|
121
|
+
<Link to={`/invoices/${invoice.id}`}>{invoice.number}</Link>
|
|
122
|
+
</li>
|
|
123
|
+
))}
|
|
124
|
+
</ul>
|
|
125
|
+
{!query.isPreviousData && query.data?.length === 0 ? (
|
|
126
|
+
<p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
|
|
127
|
+
) : null}
|
|
128
|
+
<Link to={list.href({ page: list.page + 1 })}>
|
|
129
|
+
{t('common.next', undefined, { defaultValue: 'Next page' })}
|
|
130
|
+
</Link>
|
|
131
|
+
</section>
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
62
136
|
A mutation or a failed load has to change a page that is ALREADY mounted, and
|
|
63
137
|
the cache never starts that request by itself: `set()` paints a mutation's own
|
|
64
138
|
response, `invalidate()` marks what it affects for the next mount, and an
|
|
@@ -178,7 +252,9 @@ The document for `options.key`, kept current: cached data is returned on
|
|
|
178
252
|
the very first render (so a warmed page never flashes a loading state),
|
|
179
253
|
a stale or missing document is fetched, and every change re-renders.
|
|
180
254
|
Pass `null` to observe nothing. A key change resets to that key's state;
|
|
181
|
-
the hook never hands a caller another key's document
|
|
255
|
+
the hook never hands a caller another key's document — unless the caller
|
|
256
|
+
opts into {@link QueryOptions.keepPreviousData}, and then only within one
|
|
257
|
+
{@link QueryOptions.principal}.
|
|
182
258
|
|
|
183
259
|
The request is stable across re-renders — a parent state change neither
|
|
184
260
|
restarts it nor cancels it, so a response that arrives after one still
|
|
@@ -188,13 +264,23 @@ lands. It is aborted only when the key changes or the component unmounts
|
|
|
188
264
|
whose deps include a function rebuilt each render, cancels its own request
|
|
189
265
|
on every re-render and then skips the refetch.
|
|
190
266
|
|
|
267
|
+
For a LIST, put the route's page, filter and selected view in the key and
|
|
268
|
+
pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
|
|
269
|
+
then keeps the rows already on screen until the new page answers, instead of
|
|
270
|
+
rendering a loading state over an empty list. The key names everything the
|
|
271
|
+
answer depends on, and the app's HTTP client sends the session, so a list the
|
|
272
|
+
server can filter or personalize per viewer puts the viewer in its key and
|
|
273
|
+
passes the same value as `principal` (`'anonymous'` when signed out): an
|
|
274
|
+
|
|
275
|
+
_(description truncated — read the full text in `node_modules/@molecule/app-query-react/dist/useQuery.d.ts`.)_
|
|
276
|
+
|
|
191
277
|
```typescript
|
|
192
278
|
function useQuery(options: QueryOptions<T> | null): QueryState<T>
|
|
193
279
|
```
|
|
194
280
|
|
|
195
|
-
- `options` — Key, fetch, freshness
|
|
281
|
+
- `options` — Key, fetch, freshness, and optionally `principal` with `keepPreviousData`; or `null`.
|
|
196
282
|
|
|
197
|
-
**Returns:** The document's state.
|
|
283
|
+
**Returns:** The document's state. `isPreviousData` is `true` while `data` is the previous key's document for the same principal.
|
|
198
284
|
|
|
199
285
|
## Injection Notes
|
|
200
286
|
|
|
@@ -217,6 +303,32 @@ Peer dependencies:
|
|
|
217
303
|
- **The key is the identity.** Building `options` inline is fine; the
|
|
218
304
|
hook resubscribes only when the key's value changes, not when the
|
|
219
305
|
`fetch` closure does.
|
|
306
|
+
- **A key change normally resets to the new key's state.** For a list's own
|
|
307
|
+
page/filter/view change, opt into `keepPreviousData` with a `principal`;
|
|
308
|
+
`isPreviousData` tells you the rows on screen belong to the key you just
|
|
309
|
+
left. A completed response (including an empty list) replaces them, and a
|
|
310
|
+
changed principal drops them, so an account switch never shows the previous
|
|
311
|
+
account's rows. Do not emulate this with a local `useState` mirror of the
|
|
312
|
+
query data — that mirror is what serves stale rows under a new page, or
|
|
313
|
+
blanks the list on a re-render.
|
|
314
|
+
- **The key names the viewer whenever the answer can depend on it.** The
|
|
315
|
+
app's HTTP client sends the session, so the server may filter or
|
|
316
|
+
personalize even a list that guests can see (a `favorited` or `following`
|
|
317
|
+
flag), and the cache serves a key's document to whoever observes it,
|
|
318
|
+
across sign-in and sign-out. Key such a list on the viewer
|
|
319
|
+
(`user ? String(user.id) : 'anonymous'`), pass the same value as
|
|
320
|
+
`principal`, and pass `null` while the session is still being restored
|
|
321
|
+
(`status === 'loading'`; the HTTP client holds the request until then
|
|
322
|
+
anyway), so restoring a session never swaps a key that already rendered
|
|
323
|
+
rows. A viewer-free key with `principal: 'public'` is only for an endpoint
|
|
324
|
+
that answers every viewer the same. A protected `useListRoute` view also
|
|
325
|
+
passes `null` while `canLoad` is false.
|
|
326
|
+
- **Render loading, empty and error status outside the item list**, and never
|
|
327
|
+
give a placeholder the item's own class or element shape: a list read by
|
|
328
|
+
the item class (or by `:first-child`) must contain only real items. An
|
|
329
|
+
empty array is a loaded empty state, not a missing response; render it
|
|
330
|
+
only when `isPreviousData` is not set, because a retained document belongs
|
|
331
|
+
to the key you just left.
|
|
220
332
|
- `intentPrefetchProps` spreads three handlers onto a link. It is a plain
|
|
221
333
|
function (not a hook), so it works inside `.map()` too.
|
|
222
334
|
- Prefetching respects the browser's data-saver setting and skips 2G
|
package/dist/index.d.ts
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
*
|
|
23
23
|
* @example
|
|
24
24
|
* ```tsx
|
|
25
|
+
* import { Link } from 'react-router'
|
|
25
26
|
* import { intentPrefetchProps, useQuery } from '@molecule/app-query-react'
|
|
26
27
|
*
|
|
27
28
|
* const packageQuery = (name: string) => ({
|
|
@@ -42,6 +43,80 @@
|
|
|
42
43
|
* ```
|
|
43
44
|
*
|
|
44
45
|
* @example
|
|
46
|
+
* A list whose page and filter live in the URL: derive the key from the route and pass
|
|
47
|
+
* `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
|
|
48
|
+
* until the next page answers. The app's HTTP client sends the session, so the viewer is part of
|
|
49
|
+
* what the answer depends on: key on it and pass the same value as `principal` — an account
|
|
50
|
+
* switch then drops the previous account's rows at once. Pass `null` while the session is still
|
|
51
|
+
* being restored (`status === 'loading'`; the HTTP client holds the request until then anyway),
|
|
52
|
+
* so restoring a session never swaps a key that already rendered rows.
|
|
53
|
+
*
|
|
54
|
+
* ```tsx
|
|
55
|
+
* import { Link } from 'react-router'
|
|
56
|
+
* import { unwrapList } from '@molecule/app-http'
|
|
57
|
+
* import { useQuery } from '@molecule/app-query-react'
|
|
58
|
+
* import { useAuth, useHttpClient, useTranslation } from '@molecule/app-react'
|
|
59
|
+
* import { useListRoute } from '@molecule/app-routing-react-router'
|
|
60
|
+
*
|
|
61
|
+
* interface Invoice {
|
|
62
|
+
* id: string
|
|
63
|
+
* number: string
|
|
64
|
+
* }
|
|
65
|
+
*
|
|
66
|
+
* function InvoiceList() {
|
|
67
|
+
* const http = useHttpClient()
|
|
68
|
+
* const { t } = useTranslation()
|
|
69
|
+
* const { status, user } = useAuth<{ id: string }>()
|
|
70
|
+
* const list = useListRoute({ pageSize: 20, filters: { status: {} } })
|
|
71
|
+
* const viewer = user ? String(user.id) : 'anonymous'
|
|
72
|
+
* const query = useQuery(
|
|
73
|
+
* status === 'loading' || !list.canLoad
|
|
74
|
+
* ? null
|
|
75
|
+
* : {
|
|
76
|
+
* key: ['invoices', viewer, list.filters, list.page],
|
|
77
|
+
* principal: viewer,
|
|
78
|
+
* keepPreviousData: true,
|
|
79
|
+
* fetch: async (signal: AbortSignal) =>
|
|
80
|
+
* unwrapList<Invoice>(
|
|
81
|
+
* await http.get('/api/invoices', {
|
|
82
|
+
* signal,
|
|
83
|
+
* params: { ...list.filters, limit: list.pageSize, offset: list.offset },
|
|
84
|
+
* }),
|
|
85
|
+
* ),
|
|
86
|
+
* },
|
|
87
|
+
* )
|
|
88
|
+
*
|
|
89
|
+
* // Status renders outside the item list (it is not an item), and the empty state
|
|
90
|
+
* // describes only the key on screen, never a retained previous page.
|
|
91
|
+
* return (
|
|
92
|
+
* <section>
|
|
93
|
+
* {status === 'loading' || query.isFetching ? (
|
|
94
|
+
* <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
|
|
95
|
+
* ) : null}
|
|
96
|
+
* {query.status === 'error' ? (
|
|
97
|
+
* <p role="alert">
|
|
98
|
+
* {t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}
|
|
99
|
+
* </p>
|
|
100
|
+
* ) : null}
|
|
101
|
+
* <ul>
|
|
102
|
+
* {query.data?.map((invoice) => (
|
|
103
|
+
* <li key={invoice.id}>
|
|
104
|
+
* <Link to={`/invoices/${invoice.id}`}>{invoice.number}</Link>
|
|
105
|
+
* </li>
|
|
106
|
+
* ))}
|
|
107
|
+
* </ul>
|
|
108
|
+
* {!query.isPreviousData && query.data?.length === 0 ? (
|
|
109
|
+
* <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
|
|
110
|
+
* ) : null}
|
|
111
|
+
* <Link to={list.href({ page: list.page + 1 })}>
|
|
112
|
+
* {t('common.next', undefined, { defaultValue: 'Next page' })}
|
|
113
|
+
* </Link>
|
|
114
|
+
* </section>
|
|
115
|
+
* )
|
|
116
|
+
* }
|
|
117
|
+
* ```
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
45
120
|
* A mutation or a failed load has to change a page that is ALREADY mounted, and
|
|
46
121
|
* the cache never starts that request by itself: `set()` paints a mutation's own
|
|
47
122
|
* response, `invalidate()` marks what it affects for the next mount, and an
|
|
@@ -98,6 +173,32 @@
|
|
|
98
173
|
* - **The key is the identity.** Building `options` inline is fine; the
|
|
99
174
|
* hook resubscribes only when the key's value changes, not when the
|
|
100
175
|
* `fetch` closure does.
|
|
176
|
+
* - **A key change normally resets to the new key's state.** For a list's own
|
|
177
|
+
* page/filter/view change, opt into `keepPreviousData` with a `principal`;
|
|
178
|
+
* `isPreviousData` tells you the rows on screen belong to the key you just
|
|
179
|
+
* left. A completed response (including an empty list) replaces them, and a
|
|
180
|
+
* changed principal drops them, so an account switch never shows the previous
|
|
181
|
+
* account's rows. Do not emulate this with a local `useState` mirror of the
|
|
182
|
+
* query data — that mirror is what serves stale rows under a new page, or
|
|
183
|
+
* blanks the list on a re-render.
|
|
184
|
+
* - **The key names the viewer whenever the answer can depend on it.** The
|
|
185
|
+
* app's HTTP client sends the session, so the server may filter or
|
|
186
|
+
* personalize even a list that guests can see (a `favorited` or `following`
|
|
187
|
+
* flag), and the cache serves a key's document to whoever observes it,
|
|
188
|
+
* across sign-in and sign-out. Key such a list on the viewer
|
|
189
|
+
* (`user ? String(user.id) : 'anonymous'`), pass the same value as
|
|
190
|
+
* `principal`, and pass `null` while the session is still being restored
|
|
191
|
+
* (`status === 'loading'`; the HTTP client holds the request until then
|
|
192
|
+
* anyway), so restoring a session never swaps a key that already rendered
|
|
193
|
+
* rows. A viewer-free key with `principal: 'public'` is only for an endpoint
|
|
194
|
+
* that answers every viewer the same. A protected `useListRoute` view also
|
|
195
|
+
* passes `null` while `canLoad` is false.
|
|
196
|
+
* - **Render loading, empty and error status outside the item list**, and never
|
|
197
|
+
* give a placeholder the item's own class or element shape: a list read by
|
|
198
|
+
* the item class (or by `:first-child`) must contain only real items. An
|
|
199
|
+
* empty array is a loaded empty state, not a missing response; render it
|
|
200
|
+
* only when `isPreviousData` is not set, because a retained document belongs
|
|
201
|
+
* to the key you just left.
|
|
101
202
|
* - `intentPrefetchProps` spreads three handlers onto a link. It is a plain
|
|
102
203
|
* function (not a hook), so it works inside `.map()` too.
|
|
103
204
|
* - Prefetching respects the browser's data-saver setting and skips 2G
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyNG;AAEH,cAAc,kBAAkB,CAAA;AAChC,cAAc,eAAe,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
*
|
|
23
23
|
* @example
|
|
24
24
|
* ```tsx
|
|
25
|
+
* import { Link } from 'react-router'
|
|
25
26
|
* import { intentPrefetchProps, useQuery } from '@molecule/app-query-react'
|
|
26
27
|
*
|
|
27
28
|
* const packageQuery = (name: string) => ({
|
|
@@ -42,6 +43,80 @@
|
|
|
42
43
|
* ```
|
|
43
44
|
*
|
|
44
45
|
* @example
|
|
46
|
+
* A list whose page and filter live in the URL: derive the key from the route and pass
|
|
47
|
+
* `keepPreviousData` with a `principal`, so a page/filter change keeps the rows already on screen
|
|
48
|
+
* until the next page answers. The app's HTTP client sends the session, so the viewer is part of
|
|
49
|
+
* what the answer depends on: key on it and pass the same value as `principal` — an account
|
|
50
|
+
* switch then drops the previous account's rows at once. Pass `null` while the session is still
|
|
51
|
+
* being restored (`status === 'loading'`; the HTTP client holds the request until then anyway),
|
|
52
|
+
* so restoring a session never swaps a key that already rendered rows.
|
|
53
|
+
*
|
|
54
|
+
* ```tsx
|
|
55
|
+
* import { Link } from 'react-router'
|
|
56
|
+
* import { unwrapList } from '@molecule/app-http'
|
|
57
|
+
* import { useQuery } from '@molecule/app-query-react'
|
|
58
|
+
* import { useAuth, useHttpClient, useTranslation } from '@molecule/app-react'
|
|
59
|
+
* import { useListRoute } from '@molecule/app-routing-react-router'
|
|
60
|
+
*
|
|
61
|
+
* interface Invoice {
|
|
62
|
+
* id: string
|
|
63
|
+
* number: string
|
|
64
|
+
* }
|
|
65
|
+
*
|
|
66
|
+
* function InvoiceList() {
|
|
67
|
+
* const http = useHttpClient()
|
|
68
|
+
* const { t } = useTranslation()
|
|
69
|
+
* const { status, user } = useAuth<{ id: string }>()
|
|
70
|
+
* const list = useListRoute({ pageSize: 20, filters: { status: {} } })
|
|
71
|
+
* const viewer = user ? String(user.id) : 'anonymous'
|
|
72
|
+
* const query = useQuery(
|
|
73
|
+
* status === 'loading' || !list.canLoad
|
|
74
|
+
* ? null
|
|
75
|
+
* : {
|
|
76
|
+
* key: ['invoices', viewer, list.filters, list.page],
|
|
77
|
+
* principal: viewer,
|
|
78
|
+
* keepPreviousData: true,
|
|
79
|
+
* fetch: async (signal: AbortSignal) =>
|
|
80
|
+
* unwrapList<Invoice>(
|
|
81
|
+
* await http.get('/api/invoices', {
|
|
82
|
+
* signal,
|
|
83
|
+
* params: { ...list.filters, limit: list.pageSize, offset: list.offset },
|
|
84
|
+
* }),
|
|
85
|
+
* ),
|
|
86
|
+
* },
|
|
87
|
+
* )
|
|
88
|
+
*
|
|
89
|
+
* // Status renders outside the item list (it is not an item), and the empty state
|
|
90
|
+
* // describes only the key on screen, never a retained previous page.
|
|
91
|
+
* return (
|
|
92
|
+
* <section>
|
|
93
|
+
* {status === 'loading' || query.isFetching ? (
|
|
94
|
+
* <p role="status">{t('common.loading', undefined, { defaultValue: 'Loading…' })}</p>
|
|
95
|
+
* ) : null}
|
|
96
|
+
* {query.status === 'error' ? (
|
|
97
|
+
* <p role="alert">
|
|
98
|
+
* {t('invoices.loadFailed', undefined, { defaultValue: 'Unable to load invoices.' })}
|
|
99
|
+
* </p>
|
|
100
|
+
* ) : null}
|
|
101
|
+
* <ul>
|
|
102
|
+
* {query.data?.map((invoice) => (
|
|
103
|
+
* <li key={invoice.id}>
|
|
104
|
+
* <Link to={`/invoices/${invoice.id}`}>{invoice.number}</Link>
|
|
105
|
+
* </li>
|
|
106
|
+
* ))}
|
|
107
|
+
* </ul>
|
|
108
|
+
* {!query.isPreviousData && query.data?.length === 0 ? (
|
|
109
|
+
* <p>{t('invoices.empty', undefined, { defaultValue: 'No invoices yet.' })}</p>
|
|
110
|
+
* ) : null}
|
|
111
|
+
* <Link to={list.href({ page: list.page + 1 })}>
|
|
112
|
+
* {t('common.next', undefined, { defaultValue: 'Next page' })}
|
|
113
|
+
* </Link>
|
|
114
|
+
* </section>
|
|
115
|
+
* )
|
|
116
|
+
* }
|
|
117
|
+
* ```
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
45
120
|
* A mutation or a failed load has to change a page that is ALREADY mounted, and
|
|
46
121
|
* the cache never starts that request by itself: `set()` paints a mutation's own
|
|
47
122
|
* response, `invalidate()` marks what it affects for the next mount, and an
|
|
@@ -98,6 +173,32 @@
|
|
|
98
173
|
* - **The key is the identity.** Building `options` inline is fine; the
|
|
99
174
|
* hook resubscribes only when the key's value changes, not when the
|
|
100
175
|
* `fetch` closure does.
|
|
176
|
+
* - **A key change normally resets to the new key's state.** For a list's own
|
|
177
|
+
* page/filter/view change, opt into `keepPreviousData` with a `principal`;
|
|
178
|
+
* `isPreviousData` tells you the rows on screen belong to the key you just
|
|
179
|
+
* left. A completed response (including an empty list) replaces them, and a
|
|
180
|
+
* changed principal drops them, so an account switch never shows the previous
|
|
181
|
+
* account's rows. Do not emulate this with a local `useState` mirror of the
|
|
182
|
+
* query data — that mirror is what serves stale rows under a new page, or
|
|
183
|
+
* blanks the list on a re-render.
|
|
184
|
+
* - **The key names the viewer whenever the answer can depend on it.** The
|
|
185
|
+
* app's HTTP client sends the session, so the server may filter or
|
|
186
|
+
* personalize even a list that guests can see (a `favorited` or `following`
|
|
187
|
+
* flag), and the cache serves a key's document to whoever observes it,
|
|
188
|
+
* across sign-in and sign-out. Key such a list on the viewer
|
|
189
|
+
* (`user ? String(user.id) : 'anonymous'`), pass the same value as
|
|
190
|
+
* `principal`, and pass `null` while the session is still being restored
|
|
191
|
+
* (`status === 'loading'`; the HTTP client holds the request until then
|
|
192
|
+
* anyway), so restoring a session never swaps a key that already rendered
|
|
193
|
+
* rows. A viewer-free key with `principal: 'public'` is only for an endpoint
|
|
194
|
+
* that answers every viewer the same. A protected `useListRoute` view also
|
|
195
|
+
* passes `null` while `canLoad` is false.
|
|
196
|
+
* - **Render loading, empty and error status outside the item list**, and never
|
|
197
|
+
* give a placeholder the item's own class or element shape: a list read by
|
|
198
|
+
* the item class (or by `:first-child`) must contain only real items. An
|
|
199
|
+
* empty array is a loaded empty state, not a missing response; render it
|
|
200
|
+
* only when `isPreviousData` is not set, because a retained document belongs
|
|
201
|
+
* to the key you just left.
|
|
101
202
|
* - `intentPrefetchProps` spreads three handlers onto a link. It is a plain
|
|
102
203
|
* function (not a hook), so it works inside `.map()` too.
|
|
103
204
|
* - Prefetching respects the browser's data-saver setting and skips 2G
|
package/dist/useQuery.d.ts
CHANGED
|
@@ -9,7 +9,9 @@ import type { QueryOptions, QueryState } from '@molecule/app-query';
|
|
|
9
9
|
* the very first render (so a warmed page never flashes a loading state),
|
|
10
10
|
* a stale or missing document is fetched, and every change re-renders.
|
|
11
11
|
* Pass `null` to observe nothing. A key change resets to that key's state;
|
|
12
|
-
* the hook never hands a caller another key's document
|
|
12
|
+
* the hook never hands a caller another key's document — unless the caller
|
|
13
|
+
* opts into {@link QueryOptions.keepPreviousData}, and then only within one
|
|
14
|
+
* {@link QueryOptions.principal}.
|
|
13
15
|
*
|
|
14
16
|
* The request is stable across re-renders — a parent state change neither
|
|
15
17
|
* restarts it nor cancels it, so a response that arrives after one still
|
|
@@ -19,8 +21,24 @@ import type { QueryOptions, QueryState } from '@molecule/app-query';
|
|
|
19
21
|
* whose deps include a function rebuilt each render, cancels its own request
|
|
20
22
|
* on every re-render and then skips the refetch.
|
|
21
23
|
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
+
* For a LIST, put the route's page, filter and selected view in the key and
|
|
25
|
+
* pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
|
|
26
|
+
* then keeps the rows already on screen until the new page answers, instead of
|
|
27
|
+
* rendering a loading state over an empty list. The key names everything the
|
|
28
|
+
* answer depends on, and the app's HTTP client sends the session, so a list the
|
|
29
|
+
* server can filter or personalize per viewer puts the viewer in its key and
|
|
30
|
+
* passes the same value as `principal` (`'anonymous'` when signed out): an
|
|
31
|
+
* account switch then drops the previous account's document immediately. Only
|
|
32
|
+
* an endpoint that answers every viewer the same takes a viewer-free key with
|
|
33
|
+
* `principal: 'public'`.
|
|
34
|
+
*
|
|
35
|
+
* @param options - Key, fetch, freshness, and optionally `principal` with
|
|
36
|
+
* `keepPreviousData`; or `null`.
|
|
37
|
+
* @returns The document's state. `isPreviousData` is `true` while `data` is
|
|
38
|
+
* the previous key's document for the same principal.
|
|
39
|
+
* @throws {Error} When `keepPreviousData` is set without `principal` — the
|
|
40
|
+
* hook cannot tell a route change from a principal switch, so it refuses
|
|
41
|
+
* rather than risk showing one principal's document to another.
|
|
24
42
|
*/
|
|
25
43
|
export declare function useQuery<T>(options: QueryOptions<T> | null): QueryState<T>;
|
|
26
44
|
//# sourceMappingURL=useQuery.d.ts.map
|
package/dist/useQuery.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;
|
|
1
|
+
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../src/useQuery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAwBnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC,CA0E1E"}
|
package/dist/useQuery.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
|
-
import { useEffect, useMemo, useState } from 'react';
|
|
6
|
+
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
7
7
|
import { getQueryClient, hashQueryKey } from '@molecule/app-query';
|
|
8
8
|
const IDLE = {
|
|
9
9
|
data: undefined,
|
|
@@ -17,7 +17,9 @@ const IDLE = {
|
|
|
17
17
|
* the very first render (so a warmed page never flashes a loading state),
|
|
18
18
|
* a stale or missing document is fetched, and every change re-renders.
|
|
19
19
|
* Pass `null` to observe nothing. A key change resets to that key's state;
|
|
20
|
-
* the hook never hands a caller another key's document
|
|
20
|
+
* the hook never hands a caller another key's document — unless the caller
|
|
21
|
+
* opts into {@link QueryOptions.keepPreviousData}, and then only within one
|
|
22
|
+
* {@link QueryOptions.principal}.
|
|
21
23
|
*
|
|
22
24
|
* The request is stable across re-renders — a parent state change neither
|
|
23
25
|
* restarts it nor cancels it, so a response that arrives after one still
|
|
@@ -27,11 +29,32 @@ const IDLE = {
|
|
|
27
29
|
* whose deps include a function rebuilt each render, cancels its own request
|
|
28
30
|
* on every re-render and then skips the refetch.
|
|
29
31
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
+
* For a LIST, put the route's page, filter and selected view in the key and
|
|
33
|
+
* pass `keepPreviousData` with a `principal`: a Next/Previous or filter change
|
|
34
|
+
* then keeps the rows already on screen until the new page answers, instead of
|
|
35
|
+
* rendering a loading state over an empty list. The key names everything the
|
|
36
|
+
* answer depends on, and the app's HTTP client sends the session, so a list the
|
|
37
|
+
* server can filter or personalize per viewer puts the viewer in its key and
|
|
38
|
+
* passes the same value as `principal` (`'anonymous'` when signed out): an
|
|
39
|
+
* account switch then drops the previous account's document immediately. Only
|
|
40
|
+
* an endpoint that answers every viewer the same takes a viewer-free key with
|
|
41
|
+
* `principal: 'public'`.
|
|
42
|
+
*
|
|
43
|
+
* @param options - Key, fetch, freshness, and optionally `principal` with
|
|
44
|
+
* `keepPreviousData`; or `null`.
|
|
45
|
+
* @returns The document's state. `isPreviousData` is `true` while `data` is
|
|
46
|
+
* the previous key's document for the same principal.
|
|
47
|
+
* @throws {Error} When `keepPreviousData` is set without `principal` — the
|
|
48
|
+
* hook cannot tell a route change from a principal switch, so it refuses
|
|
49
|
+
* rather than risk showing one principal's document to another.
|
|
32
50
|
*/
|
|
33
51
|
export function useQuery(options) {
|
|
34
52
|
const hash = options ? hashQueryKey(options.key) : '';
|
|
53
|
+
const principal = options?.principal;
|
|
54
|
+
const keepPreviousData = options?.keepPreviousData === true;
|
|
55
|
+
if (keepPreviousData && principal === undefined) {
|
|
56
|
+
throw new Error('useQuery: keepPreviousData requires principal — the viewer the document is for (the signed-in id, "anonymous" while signed out, or "public" for an endpoint that answers every viewer the same) so a viewer switch never shows the previous document.');
|
|
57
|
+
}
|
|
35
58
|
// Options are read once per key: a fresh `fetch` closure every render must
|
|
36
59
|
// not resubscribe.
|
|
37
60
|
const stable = useMemo(() => options, [hash]);
|
|
@@ -39,6 +62,50 @@ export function useQuery(options) {
|
|
|
39
62
|
hash,
|
|
40
63
|
value: stable ? getQueryClient().getState(stable.key) : IDLE,
|
|
41
64
|
}));
|
|
65
|
+
// The previous document is remembered ACROSS renders, so the render that
|
|
66
|
+
// first observes a new key still has the rows a person is looking at.
|
|
67
|
+
const loaded = useRef(null);
|
|
68
|
+
// A key's document belongs to the principal that was current when the hook
|
|
69
|
+
// started observing that key: a principal change the key does not reflect
|
|
70
|
+
// never relabels the document on screen as the new principal's.
|
|
71
|
+
const observed = useRef(null);
|
|
72
|
+
const current = state.hash === hash
|
|
73
|
+
? state.value
|
|
74
|
+
: stable
|
|
75
|
+
? getQueryClient().getState(stable.key)
|
|
76
|
+
: IDLE;
|
|
77
|
+
const previous = keepPreviousData ? loaded.current : null;
|
|
78
|
+
const value = previous !== null &&
|
|
79
|
+
previous.principal === principal &&
|
|
80
|
+
previous.hash !== hash &&
|
|
81
|
+
current.data === undefined &&
|
|
82
|
+
(current.status === 'idle' || current.status === 'loading')
|
|
83
|
+
? {
|
|
84
|
+
...current,
|
|
85
|
+
data: previous.value.data,
|
|
86
|
+
updatedAt: previous.value.updatedAt,
|
|
87
|
+
isPreviousData: true,
|
|
88
|
+
}
|
|
89
|
+
: current;
|
|
90
|
+
useEffect(() => {
|
|
91
|
+
if (observed.current?.hash !== hash)
|
|
92
|
+
observed.current = { hash, principal };
|
|
93
|
+
// A document is remembered only as its own principal's answer. While a
|
|
94
|
+
// retained previous document is showing, the memory is what makes it
|
|
95
|
+
// survive the fetch; keep it until this key answers. Anything else (no
|
|
96
|
+
// principal, a switch, a failure, a key observed under another principal)
|
|
97
|
+
// clears it, so a later key change can never fall back to another
|
|
98
|
+
// principal's document.
|
|
99
|
+
if (value.isPreviousData === true)
|
|
100
|
+
return;
|
|
101
|
+
loaded.current =
|
|
102
|
+
principal !== undefined &&
|
|
103
|
+
observed.current.principal === principal &&
|
|
104
|
+
value.data !== undefined &&
|
|
105
|
+
value.status === 'success'
|
|
106
|
+
? { hash, principal, value }
|
|
107
|
+
: null;
|
|
108
|
+
}, [hash, principal, value]);
|
|
42
109
|
useEffect(() => {
|
|
43
110
|
if (!stable) {
|
|
44
111
|
setState({ hash: '', value: IDLE });
|
|
@@ -47,7 +114,5 @@ export function useQuery(options) {
|
|
|
47
114
|
const client = getQueryClient();
|
|
48
115
|
return client.subscribe(stable, (value) => setState({ hash, value }));
|
|
49
116
|
}, [stable, hash]);
|
|
50
|
-
|
|
51
|
-
return state.value;
|
|
52
|
-
return stable ? getQueryClient().getState(stable.key) : IDLE;
|
|
117
|
+
return value;
|
|
53
118
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/app-query-react",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.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",
|
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
"directory": "packages/app/features/query-react"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"@molecule/app-query": "^1.
|
|
39
|
+
"@molecule/app-query": "^1.1.0",
|
|
40
40
|
"react": "^18.0.0 || ^19.0.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@molecule/app-query": "1.0
|
|
43
|
+
"@molecule/app-query": "1.1.0",
|
|
44
44
|
"@molecule/app-query-memory": "1.0.3",
|
|
45
45
|
"@molecule/app-query-tanstack": "1.0.2",
|
|
46
46
|
"@types/node": "26.6.5",
|