tsdf 16.0.3 → 17.0.0-alpha.2

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.
@@ -0,0 +1,148 @@
1
+ # Document Store
2
+
3
+ A store for managing a single entity/document. It provides one fetch function and maintains a single piece of data with loading states, error handling, and automatic refetching.
4
+
5
+ See also: [Hooks](./hooks.md) | [Mutations](./mutations.md) | [Invalidation](./invalidation.md) | [Fetch Scheduling](./fetch-scheduling.md) | [Persistent Storage](./persistent-storage.md) | [Offline](./offline.md)
6
+
7
+ ## Creating a Document Store
8
+
9
+ ```ts
10
+ import { createDocumentStore, createStoreManager } from 'tsdf';
11
+
12
+ type User = { id: string; name: string; email: string };
13
+ const storeManager = createStoreManager({
14
+ getSessionKey: () =>
15
+ authState.userId ? `tenant:${authState.tenantId}` : false,
16
+ errorNormalizer: normalizeError,
17
+ lowPriorityThrottleMs: 5,
18
+ baseCoalescingWindowMs: 10,
19
+ blockWindowClose: null,
20
+ });
21
+
22
+ const userStore = createDocumentStore<User>({
23
+ id: 'document-user',
24
+ storeManager,
25
+ fetchFn: (signal) => api.getUser(signal),
26
+ });
27
+ ```
28
+
29
+ ## Options
30
+
31
+ | Option | Type | Required | Description |
32
+ | ------------------------------ | -------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------- |
33
+ | `id` | `string` | Yes | Stable logical store id for [Browser Tabs Sync](./browser-tabs-sync.md) |
34
+ | `storeManager` | `StoreManager` | Yes | Shared global config with `getSessionKey`, `errorNormalizer`, and global store controls |
35
+ | `fetchFn` | `(signal: AbortSignal) => Promise<State>` | Yes | Fetches the document data |
36
+ | `lowPriorityThrottleMs` | `number` | No | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
37
+ | `baseCoalescingWindowMs` | `number` | No | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
38
+ | `debugName` | `string` | No | Debug name for logging |
39
+ | `dynamicRealtimeThrottleMs` | `(params: { lastFetchDuration: number; windowIsNotFocused: boolean }) => number` | No | See [Real-Time Updates](./real-time-updates.md) |
40
+ | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | No | Refetch on window focus |
41
+ | `transportReconnectCooldownMs` | `number` | No | Cooldown for repeated transport reconnect revalidation |
42
+ | `mediumPriorityDelayMs` | `number` | No | Delay for medium-priority fetches |
43
+ | `usesRealTimeUpdates` | `boolean` | No | Enables [Real-Time Updates](./real-time-updates.md) mode |
44
+ | `persistentStorage` | `DocumentPersistentStorageConfig<State>` | No | Configure cache persistence. See [Persistent Storage](./persistent-storage.md) |
45
+ | `onSchedulerEvent` | `(event) => void` | No | Scheduler event listener |
46
+ | `onMutationError` | `(error, options: { dontShowToast?: boolean }) => void` | No | Global mutation error handler |
47
+
48
+ ## State Shape
49
+
50
+ ```ts
51
+ type DocumentStoreState<State> = {
52
+ data: State | null;
53
+ error: StoreError | null;
54
+ status: 'idle' | 'loading' | 'error' | 'refetching' | 'success';
55
+ refetchOnMount:
56
+ | false
57
+ | 'lowPriority'
58
+ | 'mediumPriority'
59
+ | 'realtimeUpdate'
60
+ | 'highPriority';
61
+ };
62
+ ```
63
+
64
+ - `data` starts as `null` and is populated after a successful fetch
65
+ - `status` transitions: `idle` -> `loading` -> `success` / `error`; on refetch: `success` -> `refetching` -> `success` / `error`
66
+ - `refetchOnMount` is set by [invalidation](./invalidation.md) to trigger a refetch on next hook mount
67
+
68
+ ## API
69
+
70
+ ### Hooks
71
+
72
+ | Hook | Description | Details |
73
+ | ------------------------------- | ------------------------------------- | ------------------------------------------------------------- |
74
+ | `useDocument(options?)` | Primary data hook | See [Hooks - useDocument](./hooks.md#usedocument) |
75
+ | `useListItemIsLoading(options)` | Detect if a sub-item is loading | See [Hooks - useListItem Hooks](./hooks.md#uselistitem-hooks) |
76
+ | `useListItemIsDeleted(options)` | Detect if a sub-item was deleted | See [Hooks - useListItem Hooks](./hooks.md#uselistitem-hooks) |
77
+ | `useListItem(options)` | Combined loading + deletion detection | See [Hooks - useListItem Hooks](./hooks.md#uselistitem-hooks) |
78
+
79
+ ### Methods
80
+
81
+ | Method | Signature | Description |
82
+ | -------------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
83
+ | `scheduleFetch` | `(fetchType, options?) => ScheduleFetchResults` | Schedule a fetch. See [Fetch Scheduling](./fetch-scheduling.md) |
84
+ | `awaitFetch` | `(options?) => Promise<{ data, error }>` | Await a fetch with optional `timeoutMs` |
85
+ | `getDataFromStateOrFetch` | `(options?) => Promise<Result<State, StoreFetchError>>` | Return loaded state or fetch it if missing |
86
+ | `preloadPersistentStorage` | `() => Promise<void>` | Preload cached document data from async storage (OPFS) |
87
+ | `invalidateData` | `(priority?) => void` | Invalidate data. See [Invalidation](./invalidation.md) |
88
+ | `updateState` | `(produceFn) => boolean` | Immer-based state update. Returns `false` if no data exists |
89
+ | `reset` | `() => void` | Reset store to idle state |
90
+ | `startMutation` | `() => () => boolean` | Manually start a mutation lock. See [Mutations](./mutations.md) |
91
+ | `performMutation` | `(options) => Promise<Result<T>>` | Full mutation lifecycle. See [Mutations](./mutations.md) |
92
+ | `onTransportReconnect` | `() => void` | Store-level reconnect hook. Prefer `storeManager.onTransportReconnect()` for shared transports. See [Real-Time Updates](./real-time-updates.md) |
93
+
94
+ ### Offline Methods
95
+
96
+ | Method | Description |
97
+ | ----------------------------------------------------- | ----------------------------------------------------------------- |
98
+ | `getOfflineEntities()` / `useOfflineEntities()` | Read offline entities scoped to this store |
99
+ | `getOfflineResolutions()` / `useOfflineResolutions()` | Read manual conflict/retry resolutions scoped to this store |
100
+ | `parseOfflineResolutionConflict(resolution)` | Narrow a persisted resolution to this store's operation types |
101
+ | `resolveOfflineResolution(id, operation, action)` | Resolve, retry, discard, requeue, or commit an offline resolution |
102
+
103
+ ### Properties
104
+
105
+ | Property | Type | Description |
106
+ | ------------- | ----------------------------------- | ---------------------------------------------------------- |
107
+ | `store` | `Store<DocumentStoreState<State>>` | Underlying t-state store |
108
+ | `events` | `Emitter` | Invalidation events |
109
+ | `storeEvents` | `Emitter<DocumentStoreStoreEvents>` | Mutation lifecycle events (`mutationStart`, `mutationEnd`) |
110
+
111
+ ## Usage Example
112
+
113
+ ```tsx
114
+ const storeManager = createStoreManager({
115
+ getSessionKey: () =>
116
+ authState.userId ? `tenant:${authState.tenantId}` : false,
117
+ errorNormalizer: normalizeError,
118
+ lowPriorityThrottleMs: 5,
119
+ baseCoalescingWindowMs: 10,
120
+ blockWindowClose: null,
121
+ });
122
+
123
+ const settingsStore = createDocumentStore<AppSettings>({
124
+ id: 'document-settings',
125
+ storeManager,
126
+ fetchFn: (signal) => api.getSettings(signal),
127
+ lowPriorityThrottleMs: 5000,
128
+ baseCoalescingWindowMs: 200,
129
+ revalidateOnWindowFocus: true,
130
+ });
131
+
132
+ function Settings() {
133
+ const { data, isLoading, error } = settingsStore.useDocument();
134
+
135
+ if (isLoading) return <Spinner />;
136
+ if (error) return <Error error={error} />;
137
+
138
+ return <SettingsForm data={data} />;
139
+ }
140
+
141
+ // Update state locally (immer-based)
142
+ settingsStore.updateState((draft) => {
143
+ draft.theme = 'dark';
144
+ });
145
+
146
+ // Invalidate to trigger refetch
147
+ settingsStore.invalidateData();
148
+ ```
@@ -0,0 +1,93 @@
1
+ # Fetch Scheduling
2
+
3
+ TSDF uses a `RequestScheduler` to intelligently manage when and how fetches are executed. The scheduler handles priority levels, throttling, coalescing, batching, and mutation coordination.
4
+
5
+ ## Priority Levels
6
+
7
+ Every fetch request has a priority that determines its behavior:
8
+
9
+ | Priority | When used | Behavior |
10
+ | ---------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
11
+ | `lowPriority` | Hook mount (default), window focus revalidation | Throttled — skipped if a fetch happened recently (within `lowPriorityThrottleMs`) |
12
+ | `mediumPriority` | Background refetches | Delayed by `mediumPriorityDelayMs`, then executed. Cancelled if another fetch starts. If the store has never been fetched, automatically promotes to `highPriority` |
13
+ | `realtimeUpdate` | Real-time data pushes | Uses `dynamicRealtimeThrottleMs` for adaptive throttling based on last fetch duration |
14
+ | `highPriority` | Explicit invalidation, `ensureIsLoaded` | Executes immediately (after coalescing window). Never throttled |
15
+
16
+ ## Throttling
17
+
18
+ Low-priority fetches are throttled to avoid redundant requests:
19
+
20
+ ```
21
+ lowPriorityThrottleMs: 5
22
+ ```
23
+
24
+ If a hook mounts within the configured throttle window after the last fetch completed, the low-priority fetch is **skipped** because the data is still fresh enough.
25
+
26
+ ## Coalescing
27
+
28
+ When multiple fetch requests arrive in a short window, they are coalesced into a single batch:
29
+
30
+ ```
31
+ baseCoalescingWindowMs: 10
32
+ ```
33
+
34
+ If three `useItem` hooks mount within the configured coalescing window, their fetches are grouped and executed as one request (when using batch fetching) or sequentially but without duplicate requests for the same item.
35
+
36
+ ### Background Tabs
37
+
38
+ When synced browser tabs are open, TSDF can extend coalescing internally for background tabs based on focus ranking. Focused tabs keep `baseCoalescingWindowMs`; background tabs may wait longer so duplicate background work can be dropped when another tab is already fetching the same data.
39
+
40
+ See [Browser Tabs Sync](./browser-tabs-sync.md) for focus ranking and request deduplication behavior across tabs.
41
+
42
+ ## Scheduler Phases
43
+
44
+ The scheduler is a state machine with three phases:
45
+
46
+ 1. **Idle** - No pending fetches. New requests start the coalescing window.
47
+ 2. **Coalescing** - Collecting requests within the coalescing window. New requests are added to the current batch.
48
+ 3. **Fetching** - The batch is being executed. New requests are queued for the next cycle.
49
+
50
+ ## Mutation Coordination
51
+
52
+ When a mutation is in progress for an item, the scheduler prevents conflicting fetches:
53
+
54
+ - New fetch requests for the mutating item are deferred to `scheduled` state
55
+ - If a fetch is already in progress when a mutation starts, the fetch is aborted
56
+ - After the mutation completes, deferred fetches execute automatically
57
+
58
+ This prevents race conditions where a fetch could overwrite optimistic updates.
59
+
60
+ ## Medium Priority Behavior
61
+
62
+ Medium-priority fetches have special behavior:
63
+
64
+ 1. The fetch is delayed by `mediumPriorityDelayMs`
65
+ 2. If another fetch (of any priority) starts during the delay, the medium-priority fetch is cancelled
66
+ 3. If the store has never been fetched (`wasLoaded === false`), the fetch is promoted to `highPriority` immediately
67
+
68
+ This is useful for background refetches that should yield to user-initiated actions.
69
+
70
+ ## Configuration Reference
71
+
72
+ | Option | Required | Description |
73
+ | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------- |
74
+ | `lowPriorityThrottleMs` | No | Manager default minimum interval between low-priority fetches, or a store-level override. Defaults to `5` |
75
+ | `baseCoalescingWindowMs` | No | Manager default time window to group multiple requests into a single batch, or a store-level override. Defaults to `10` |
76
+ | `mediumPriorityDelayMs` | No | Delay before medium-priority fetches execute |
77
+ | `dynamicRealtimeThrottleMs` | No | Function returning throttle duration for real-time updates. See [Real-Time Updates](./real-time-updates.md) |
78
+ | `maxBatchSize` | No | (Collection/ListQuery) Triggers immediate fetch when batch size is reached, skipping the coalescing window |
79
+
80
+ ## Typical Configuration
81
+
82
+ ```ts
83
+ {
84
+ // Skip refetch if one happened in the last 5ms
85
+ lowPriorityThrottleMs: 5,
86
+
87
+ // Group fetches within 10ms
88
+ baseCoalescingWindowMs: 10,
89
+
90
+ // Wait 300ms before executing medium-priority fetches
91
+ mediumPriorityDelayMs: 300,
92
+ }
93
+ ```
package/docs/hooks.md ADDED
@@ -0,0 +1,416 @@
1
+ # React Hooks
2
+
3
+ All TSDF stores provide React hooks that automatically manage data fetching, subscriptions, and re-rendering. Hooks trigger fetches on mount and respond to invalidation events.
4
+
5
+ ## Common Hook Behaviors
6
+
7
+ All hooks share these behaviors:
8
+
9
+ - **Auto-fetch on mount**: When a hook mounts, it schedules a fetch based on the store's current state
10
+ - **Refetch on invalidation**: When data is invalidated, mounted hooks automatically refetch
11
+ - **Deep equality**: Hook return values use deep equality comparison to prevent unnecessary re-renders
12
+ - **Disabled state**: Passing a falsy payload (`null`, `undefined`, `false`) disables the hook — no fetch is triggered and the status is `idle`
13
+
14
+ ## Common Hook Options
15
+
16
+ These options are available across all data hooks:
17
+
18
+ | Option | Default | Behavior |
19
+ | -------------------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
20
+ | `disabled` / `isOffScreen` | `false` | When `true`, the hook does not trigger any fetches or respond to invalidation. Also respects the [IsOffScreenContext](./shared-types.md#isoffscreencontext) |
21
+ | `disableRefetches` | `false` | Only fetches data if it has never been loaded (status is `idle` or `error`). Skips all refetches, even from invalidation |
22
+ | `disableRefetchOnMount` | `false` (or `true` when `usesRealTimeUpdates` is enabled) | Only fetches if data was explicitly invalidated or has never been loaded. Skips the low-priority refetch that normally happens on mount |
23
+ | `returnIdleStatus` | `true` when disabled, `false` otherwise | When `false`, maps `idle` status to `loading` so the UI shows a loading state immediately |
24
+ | `returnRefetchingStatus` | `false` | When `false`, maps `refetching` status to `success` so the UI doesn't flicker during background refetches |
25
+ | `ensureIsLoaded` | `false` | Forces a high-priority fetch on mount and overrides status to `loading` until data is loaded. Useful for components that must show fresh data |
26
+
27
+ ## `debouncePayload`
28
+
29
+ Payload-based hooks support `debouncePayload` to debounce automatic fetches
30
+ caused by rapid payload changes.
31
+
32
+ This applies to:
33
+
34
+ - `useItem`
35
+ - `useListQuery`
36
+ - `useMultipleItems`
37
+ - `useMultipleListQueries`
38
+
39
+ Behavior:
40
+
41
+ - The hook still reads from state using the latest payload immediately
42
+ - Only the automatic fetch side is delayed
43
+ - Cached data for the latest payload is still returned right away when present
44
+ - Intermediate payloads are skipped if they are replaced before the debounce
45
+ window ends
46
+ - `useItem` and `useListQuery` throw if `debouncePayload` is combined with
47
+ `ensureIsLoaded`
48
+
49
+ ### Basic trailing debounce
50
+
51
+ ```tsx
52
+ const result = store.useListQuery(filter, { debouncePayload: { ms: 200 } });
53
+ ```
54
+
55
+ This waits `200ms` after the last payload change before fetching.
56
+
57
+ ### `leading`
58
+
59
+ ```tsx
60
+ const result = store.useItem(itemId, {
61
+ debouncePayload: { ms: 300, leading: true },
62
+ });
63
+ ```
64
+
65
+ With `leading: true`:
66
+
67
+ - The first payload in a burst may fetch immediately
68
+ - Later payload changes inside the same burst stay debounced
69
+ - When the debounce window ends, TSDF fetches the latest payload
70
+
71
+ ### `maxWait`
72
+
73
+ ```tsx
74
+ const result = store.useListQuery(filter, {
75
+ debouncePayload: { ms: 300, maxWait: 1000 },
76
+ });
77
+ ```
78
+
79
+ `maxWait` limits how long a burst may stay deferred. Even if payload changes
80
+ keep happening inside the debounce window, TSDF fetches the latest payload once
81
+ `maxWait` is reached.
82
+
83
+ ## useDocument
84
+
85
+ **Store**: [Document Store](./document-store.md)
86
+
87
+ Returns the document data with loading/error states.
88
+
89
+ ```tsx
90
+ const { data, status, error, isLoading } = store.useDocument();
91
+ ```
92
+
93
+ ### With selector
94
+
95
+ ```tsx
96
+ const userName = store.useDocument({
97
+ selector: (data) => data?.name ?? 'Unknown',
98
+ });
99
+ // userName.data is a string
100
+ ```
101
+
102
+ ### Disabling fetches
103
+
104
+ ```tsx
105
+ // Don't refetch if already loaded
106
+ store.useDocument({ disableRefetches: true });
107
+
108
+ // Don't refetch on mount, only when invalidated
109
+ store.useDocument({ disableRefetchOnMount: true });
110
+
111
+ // Completely disable
112
+ store.useDocument({ disabled: true });
113
+ ```
114
+
115
+ ### Return value
116
+
117
+ - `data` - The selected data (or `null` if not loaded)
118
+ - `status` - `'idle'` | `'loading'` | `'success'` | `'error'` | `'refetching'`
119
+ - `error` - The `StoreError` if the fetch failed, otherwise `null`
120
+ - `isLoading` - Shorthand for `status === 'loading'`
121
+ - `pendingSync` - `true` while local offline changes for this document still need to sync to the server
122
+
123
+ ## useItem
124
+
125
+ **Stores**: [Collection Store](./collection-store.md), [List Query Store](./list-query-store.md)
126
+
127
+ Fetches and subscribes to a single item by its payload.
128
+
129
+ ```tsx
130
+ const { data, status, error, isLoading, payload } = store.useItem('item-id');
131
+ ```
132
+
133
+ ### Disabling with falsy payload
134
+
135
+ ```tsx
136
+ // Disabled when productId is null/undefined/false — no fetch triggered
137
+ const product = store.useItem(productId ?? null);
138
+ ```
139
+
140
+ ### Empty string payload
141
+
142
+ Passing an empty string `''` as payload returns an immediate error state with `{ code: 461, id: 'invalid-payload' }` without triggering a fetch.
143
+
144
+ ### With selector
145
+
146
+ ```tsx
147
+ const itemName = store.useItem('item-1', { selector: (data) => data?.name });
148
+ ```
149
+
150
+ ### Debouncing payload changes
151
+
152
+ ```tsx
153
+ const item = store.useItem(selectedItemId, {
154
+ debouncePayload: { ms: 250, leading: true, maxWait: 1000 },
155
+ });
156
+ ```
157
+
158
+ This is useful when `selectedItemId` changes rapidly, such as typeahead-driven
159
+ selection or fast keyboard navigation.
160
+
161
+ `ensureIsLoaded` cannot be combined with `debouncePayload` on single hooks.
162
+
163
+ ### List Query Store specific options
164
+
165
+ - `loadFromStateOnly` - Don't fetch; return a cache-miss error (`{ code: 460, id: 'cache-miss' }`) if the item isn't already in the store
166
+ - `fields` - When [Partial Resources](./partial-resources.md) is enabled, specifies which fields to fetch
167
+ - `showPartialAsRefetching` - When requesting new fields on an item that already has some cached fields, keep the cached data visible and expose the pending fields via `loadingFields` instead of returning `null` / `loading`
168
+
169
+ ### Return value
170
+
171
+ - `data` - The selected data (or `null`)
172
+ - `status` - `'idle'` | `'loading'` | `'success'` | `'error'` | `'refetching'` | `'deleted'`
173
+ - `error` - The `StoreError` if the fetch failed
174
+ - `isLoading` - Shorthand for `status === 'loading'`
175
+ - `payload` - The resolved payload
176
+ - `itemStateKey` - The internal key for this item
177
+ - `loadingFields` - (List Query Store, partial resources) Requested fields that are still pending while cached data remains visible
178
+ - `pendingSync` - `true` while local offline changes for this item still need to sync to the server
179
+ - `queryMetadata` - Optional metadata passed via `useMultipleItems`
180
+
181
+ The `'deleted'` status is returned when the item's state is explicitly set to `null` (via `deleteItemState`).
182
+
183
+ ## useListQuery
184
+
185
+ **Store**: [List Query Store](./list-query-store.md)
186
+
187
+ Fetches and subscribes to a paginated list query.
188
+
189
+ ```tsx
190
+ const { items, status, hasMore, isLoading, isLoadingMore } = store.useListQuery(
191
+ { projectId: 'proj-1', status: 'active' },
192
+ );
193
+ ```
194
+
195
+ ### Disabling with falsy payload
196
+
197
+ ```tsx
198
+ // Disabled when filter is null
199
+ const result = store.useListQuery(filter ?? null);
200
+ ```
201
+
202
+ ### With item selector
203
+
204
+ Transform each item in the list:
205
+
206
+ ```tsx
207
+ const result = store.useListQuery(filter, {
208
+ itemSelector: (item) => ({ id: item.id, label: item.name }),
209
+ });
210
+ // result.items is { id: string; label: string }[]
211
+ ```
212
+
213
+ ### Custom load size
214
+
215
+ ```tsx
216
+ store.useListQuery(filter, { loadSize: 20 }); // override defaultQuerySize
217
+ ```
218
+
219
+ ### Debouncing query changes
220
+
221
+ ```tsx
222
+ const result = store.useListQuery(
223
+ { search, status: 'open' },
224
+ { debouncePayload: { ms: 300, maxWait: 1200 } },
225
+ );
226
+ ```
227
+
228
+ `ensureIsLoaded` cannot be combined with `debouncePayload` on `useListQuery`.
229
+
230
+ This is useful for search forms and filter panels where the query payload
231
+ changes on every keystroke.
232
+
233
+ ### Partial-resources options
234
+
235
+ - `fields` - When [Partial Resources](./partial-resources.md) is enabled, specifies which fields to fetch
236
+ - `showPartialAsRefetching` - When requesting new fields on a query whose items already have some cached fields, keep the cached items visible and expose the pending fields via `loadingFields` instead of returning `loading`
237
+
238
+ ### Return value
239
+
240
+ - `items` - Array of items (or selected items)
241
+ - `status` - `'idle'` | `'loading'` | `'success'` | `'error'` | `'refetching'` | `'loadingMore'`
242
+ - `fields` - The resolved partial-resource fields for this query (when partial resources is enabled this is required, otherwise `FieldsInput | undefined`)
243
+ - `loadingFields` - Requested partial-resource fields still pending while cached data remains visible
244
+ - `hasMore` - Whether more items are available for pagination
245
+ - `isDerived` - Whether the result is currently coming from `derivedQueries` instead of an exact cached/fetched query
246
+ - `isLoading` - Shorthand for `status === 'loading'`
247
+ - `isLoadingMore` - Shorthand for `status === 'loadingMore'`
248
+ - `error` - The `StoreError` if the fetch failed
249
+ - `payload` - The resolved payload
250
+ - `queryKey` - The internal key for this query
251
+ - `pendingSync` - `true` while local offline changes for this query still need to sync to the server
252
+ - `queryMetadata` - Optional metadata passed via `useMultipleListQueries`
253
+
254
+ Notes:
255
+
256
+ - Derived results are hook-level computed views and do not materialize `state.queries[queryKey]`
257
+ - Derived results always expose `hasMore: false`
258
+
259
+ ## usePendingOfflineItems
260
+
261
+ **Store**: [List Query Store](./list-query-store.md)
262
+
263
+ Returns the current offline-tracked list items for the store without fetching.
264
+ This is useful when you want to show queued offline creates, updates, and
265
+ deletes independently from any mounted `useListQuery(...)`.
266
+
267
+ ```tsx
268
+ const { items, deletedItems } = store.usePendingOfflineItems({
269
+ selector: (item) => ({ id: item.id, name: item.name }),
270
+ });
271
+ ```
272
+
273
+ Behavior:
274
+
275
+ - Returns visible pending creates and updates through `items`
276
+ - Returns pending deletes through `deletedItems`
277
+ - Uses the offline entity lifecycle kind to classify deletes before item
278
+ hydration is needed
279
+ - Does not fetch, preload queries, or expose loading state
280
+ - Reacts to offline queue changes, replay, and offline overlay updates
281
+ - Can hydrate from persisted offline state on cold startup, including when the
282
+ app boots offline and no list query has mounted yet
283
+
284
+ ### Options
285
+
286
+ - `selector` - Maps each visible pending item before returning it
287
+ - `filterPayload` - Filters entries by item payload before they are added to
288
+ `items` or `deletedItems`
289
+ - `includeResolutionRequired` - Includes entries currently blocked in
290
+ manual-resolution state. By default those entries are hidden
291
+
292
+ ### Return value
293
+
294
+ - `items` - Visible pending items (or selected items)
295
+ - `deletedItems` - Payloads for pending deletes
296
+
297
+ ## useMultipleItems
298
+
299
+ **Stores**: [Collection Store](./collection-store.md), [List Query Store](./list-query-store.md)
300
+
301
+ Fetches and subscribes to multiple items. Each item can have its own options.
302
+
303
+ ```tsx
304
+ const items = store.useMultipleItems([
305
+ { payload: 'item-1' },
306
+ { payload: 'item-2', disableRefetches: true },
307
+ { payload: 'item-3', isOffScreen: true },
308
+ ]);
309
+ // items[0].data, items[1].data, etc.
310
+ ```
311
+
312
+ Per-item options override the global options passed to the hook.
313
+
314
+ You can debounce automatic fetches for rapid item-array changes:
315
+
316
+ ```tsx
317
+ const items = store.useMultipleItems(
318
+ selectedIds.map((payload) => ({ payload })),
319
+ { debouncePayload: { ms: 150 } },
320
+ );
321
+ ```
322
+
323
+ ## useMultipleListQueries
324
+
325
+ **Store**: [List Query Store](./list-query-store.md)
326
+
327
+ Fetches and subscribes to multiple list queries.
328
+
329
+ ```tsx
330
+ const queries = store.useMultipleListQueries([
331
+ { payload: { projectId: 'proj-1' } },
332
+ { payload: { projectId: 'proj-2' }, loadSize: 10 },
333
+ ]);
334
+ // queries[0].items, queries[1].items, etc.
335
+ ```
336
+
337
+ You can debounce automatic fetches for rapid query-array changes:
338
+
339
+ ```tsx
340
+ const queries = store.useMultipleListQueries(queryInputs, {
341
+ debouncePayload: { ms: 200, maxWait: 1000 },
342
+ });
343
+ ```
344
+
345
+ ## useFindItem
346
+
347
+ **Store**: [List Query Store](./list-query-store.md)
348
+
349
+ Finds a single item across all items in the store by a predicate. Does not trigger any fetch — only searches the existing state.
350
+
351
+ ```tsx
352
+ const activeTask = store.useFindItem((item) => item.isActive, {
353
+ selector: (item) => item.title,
354
+ });
355
+ // activeTask is string | null
356
+ ```
357
+
358
+ ## useListItem Hooks
359
+
360
+ These hooks detect loading and deletion states for sub-items within a store's data. Useful when a document or collection item contains a nested list, and you need to display individual items from that list.
361
+
362
+ Available on: [Document Store](./document-store.md), [Collection Store](./collection-store.md)
363
+
364
+ ### useListItemIsLoading
365
+
366
+ Returns `true` if a sub-item is still loading.
367
+
368
+ ```tsx
369
+ const isLoading = store.useListItemIsLoading({
370
+ itemId: 'sub-item-1',
371
+ selector: (data) => data?.subItems?.find((i) => i.id === 'sub-item-1'),
372
+ });
373
+ ```
374
+
375
+ Behavior:
376
+
377
+ 1. If the sub-item exists in the data, returns `false`
378
+ 2. If the sub-item is missing and the parent data is still loading, returns `true`
379
+ 3. After 100ms timeout, if the sub-item is still missing and no refetch is in progress, calls `loadItemFallback` (defaults to `invalidateData()` / `invalidateItem()`)
380
+ 4. After 1000ms, stops showing loading to prevent infinite loading states
381
+
382
+ ### useListItemIsDeleted
383
+
384
+ Returns `true` when a sub-item that previously existed disappears from the data (not during initial loading).
385
+
386
+ ```tsx
387
+ const isDeleted = store.useListItemIsDeleted({
388
+ itemId: 'sub-item-1',
389
+ selector: (data) => data?.subItems?.find((i) => i.id === 'sub-item-1'),
390
+ onDelete: () => navigate('/list'),
391
+ });
392
+ ```
393
+
394
+ ### useListItem
395
+
396
+ Combines `useListItemIsLoading` and `useListItemIsDeleted`:
397
+
398
+ ```tsx
399
+ const { isLoading, isDeleted, data } = store.useListItem({
400
+ itemId: 'sub-item-1',
401
+ selector: (data) => data?.subItems?.find((i) => i.id === 'sub-item-1'),
402
+ onDelete: () => navigate('/list'),
403
+ });
404
+ ```
405
+
406
+ For Collection Store, these hooks take the item payload as the first argument:
407
+
408
+ ```tsx
409
+ const { isLoading, isDeleted, data } = collectionStore.useListItem(
410
+ 'item-payload',
411
+ {
412
+ itemId: 'sub-item-1',
413
+ selector: (data) => data?.nested?.find((i) => i.id === 'sub-item-1'),
414
+ },
415
+ );
416
+ ```