tsdf 16.0.3 → 17.0.0-alpha.10

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.
Files changed (39) hide show
  1. package/LICENSE +140 -0
  2. package/README.md +5 -0
  3. package/dist/async-storage.d.ts +2 -0
  4. package/dist/async-storage.js +2 -0
  5. package/dist/asyncStorageAdapter-BMYAF6rt.d.ts +6 -0
  6. package/dist/asyncStorageAdapter-BZSj1ZO5.js +1868 -0
  7. package/dist/asyncStorageAdapters-DbyKyARM.js +3 -0
  8. package/dist/indexed-db-storage.d.ts +14 -0
  9. package/dist/indexed-db-storage.js +2 -0
  10. package/dist/indexedDbPersistentStorage-DlUjN1qY.js +902 -0
  11. package/dist/main.d.ts +1487 -373
  12. package/dist/main.js +16146 -2475
  13. package/dist/opfs-storage.d.ts +2 -0
  14. package/dist/opfs-storage.js +2 -0
  15. package/dist/opfsPersistentStorage-BO_uDxe4.js +838 -0
  16. package/dist/opfsPersistentStorage-CBnUebnf.d.ts +6 -0
  17. package/dist/types-2zQlbxtw.d.ts +1475 -0
  18. package/docs/README.md +98 -0
  19. package/docs/batch-fetching.md +125 -0
  20. package/docs/browser-tabs-sync.md +61 -0
  21. package/docs/cache-limits.md +105 -0
  22. package/docs/collection-store.md +173 -0
  23. package/docs/document-store.md +149 -0
  24. package/docs/fetch-scheduling.md +93 -0
  25. package/docs/hooks.md +416 -0
  26. package/docs/invalidation.md +135 -0
  27. package/docs/list-query-store.md +352 -0
  28. package/docs/mutations.md +266 -0
  29. package/docs/offline.md +207 -0
  30. package/docs/offset-pagination.md +111 -0
  31. package/docs/optimistic-list-updates.md +180 -0
  32. package/docs/partial-resources.md +168 -0
  33. package/docs/persistent-storage.md +290 -0
  34. package/docs/real-time-updates.md +158 -0
  35. package/docs/shared-types.md +181 -0
  36. package/docs/store-manager.md +147 -0
  37. package/package.json +81 -47
  38. package/dist/main.cjs +0 -2511
  39. package/dist/main.d.cts +0 -400
@@ -0,0 +1,135 @@
1
+ # Invalidation
2
+
3
+ Invalidation marks data as stale, causing mounted hooks to refetch and future hook mounts to trigger fresh fetches. TSDF provides granular invalidation control across all store types.
4
+
5
+ ## How Invalidation Works
6
+
7
+ When data is invalidated:
8
+
9
+ 1. The `refetchOnMount` flag is set to the invalidation priority on the affected data
10
+ 2. An invalidation event is emitted
11
+ 3. Any currently mounted hooks listening for that event schedule a refetch at the specified priority
12
+ 4. If no hooks are mounted, the `refetchOnMount` flag ensures the next mount triggers a fetch
13
+
14
+ Multiple invalidations are coalesced: if data already has a pending invalidation at the same or higher priority, the new invalidation is skipped.
15
+
16
+ ## Document Store
17
+
18
+ ```ts
19
+ // Invalidate with high priority (default)
20
+ store.invalidateData();
21
+
22
+ // Invalidate with specific priority
23
+ store.invalidateData('lowPriority');
24
+ store.invalidateData('realtimeUpdate');
25
+ ```
26
+
27
+ ## Collection Store
28
+
29
+ ```ts
30
+ // Single item
31
+ store.invalidateItem('item-1');
32
+
33
+ // Multiple items
34
+ store.invalidateItem(['item-1', 'item-2']);
35
+
36
+ // By filter
37
+ store.invalidateItem((payload, data) => data?.category === 'electronics');
38
+
39
+ // With specific priority
40
+ store.invalidateItem('item-1', 'lowPriority');
41
+ ```
42
+
43
+ ## List Query Store
44
+
45
+ The List Query Store has the most flexible invalidation through `invalidateQueryAndItems`:
46
+
47
+ ```ts
48
+ import { GET_ALL } from 'tsdf';
49
+
50
+ // Invalidate all queries and all items
51
+ store.invalidateQueryAndItems({ all: true });
52
+
53
+ // Invalidate specific queries only (skip items)
54
+ store.invalidateQueryAndItems({
55
+ queryPayload: { projectId: 'proj-1' },
56
+ itemPayload: false,
57
+ });
58
+
59
+ // Invalidate specific items only (skip queries)
60
+ store.invalidateQueryAndItems({
61
+ queryPayload: false,
62
+ itemPayload: ['task-1', 'task-2'],
63
+ });
64
+
65
+ // Invalidate by filter
66
+ store.invalidateQueryAndItems({
67
+ queryPayload: (query) => query.status === 'active',
68
+ itemPayload: (item, payload) => item.priority > 5,
69
+ type: 'lowPriority',
70
+ });
71
+
72
+ // Reuse the all-payload predicate when only one side should match everything
73
+ store.invalidateQueryAndItems({ queryPayload: GET_ALL, itemPayload: false });
74
+ ```
75
+
76
+ ### Item-only invalidation
77
+
78
+ ```ts
79
+ // Shorthand for invalidating only items (no queries)
80
+ store.invalidateItem('task-1');
81
+ store.invalidateItem(['task-1', 'task-2']);
82
+ store.invalidateItem((item, payload) => item.stale);
83
+ ```
84
+
85
+ Note: `invalidateItem` requires `fetchItemFn` to be configured. Without it, item invalidation is a no-op.
86
+
87
+ ### Per-field Invalidation
88
+
89
+ When [Partial Resources](./partial-resources.md) is enabled, you can invalidate specific fields:
90
+
91
+ ```ts
92
+ store.invalidateQueryAndItems({
93
+ queryPayload: false,
94
+ itemPayload: 'task-1',
95
+ fields: ['name', 'description'], // only these fields are refetched
96
+ });
97
+ ```
98
+
99
+ This removes the specified fields from the item's loaded fields tracking, causing hooks requesting those fields to refetch them.
100
+
101
+ ## Invalidation Priority
102
+
103
+ Invalidation respects the [fetch priority system](./fetch-scheduling.md):
104
+
105
+ | Priority | Typical use |
106
+ | ---------------- | --------------------------------------------- |
107
+ | `highPriority` | User action, explicit refresh (default) |
108
+ | `lowPriority` | Window focus revalidation, background updates |
109
+ | `realtimeUpdate` | WebSocket push notifications |
110
+
111
+ If data already has a pending invalidation at equal or higher priority, a new invalidation at a lower priority is ignored.
112
+
113
+ ## Interaction with Hooks
114
+
115
+ ### disableRefetches
116
+
117
+ When a hook has `disableRefetches: true`, it ignores invalidation events **unless** the store status is `idle` or `error`. This means the hook only fetches on initial load or after errors.
118
+
119
+ ### disableRefetchOnMount
120
+
121
+ When a hook has `disableRefetchOnMount: true`, it only fetches when:
122
+
123
+ - The data has never been loaded (`status === 'idle'`)
124
+ - The data was explicitly invalidated (`refetchOnMount` is set)
125
+
126
+ It skips the default low-priority fetch that normally occurs on every mount.
127
+
128
+ ## Automatic Invalidation
129
+
130
+ TSDF automatically invalidates data in these scenarios:
131
+
132
+ - **Mutation error**: After a failed mutation, affected data is invalidated to revert optimistic updates
133
+ - **Mutation success with `revalidateOnSuccess`**: Affected data is invalidated to fetch the server's actual state
134
+ - **Window focus**: When `revalidateOnWindowFocus` is enabled, all data is invalidated with `lowPriority`
135
+ - **Transport reconnect**: When `onTransportReconnect()` is called, all data is invalidated with `realtimeUpdate` priority. See [Real-Time Updates](./real-time-updates.md)
@@ -0,0 +1,352 @@
1
+ # List Query Store
2
+
3
+ The most feature-rich store type. It manages paginated lists (queries) combined with individual item queries. Items are shared across queries, so updating an item in one query automatically reflects in all other queries that reference it.
4
+
5
+ See also: [Hooks](./hooks.md) | [Mutations](./mutations.md) | [Invalidation](./invalidation.md) | [Optimistic List Updates](./optimistic-list-updates.md) | [Partial Resources](./partial-resources.md) | [Offset Pagination](./offset-pagination.md) | [Batch Fetching](./batch-fetching.md) | [Cache Limits](./cache-limits.md) | [Persistent Storage](./persistent-storage.md) | [Offline](./offline.md)
6
+
7
+ ## Creating a List Query Store
8
+
9
+ ```ts
10
+ import { createListQueryStore, createStoreManager } from 'tsdf';
11
+
12
+ type Task = {
13
+ id: string;
14
+ title: string;
15
+ status: 'todo' | 'done';
16
+ priority: number;
17
+ };
18
+ type TaskFilter = { status?: 'todo' | 'done'; projectId: string };
19
+ const storeManager = createStoreManager({
20
+ getSessionKey: () =>
21
+ authState.userId ? `tenant:${authState.tenantId}` : false,
22
+ errorNormalizer: normalizeError,
23
+ lowPriorityThrottleMs: 5,
24
+ baseCoalescingWindowMs: 10,
25
+ blockWindowClose: null,
26
+ });
27
+
28
+ const taskStore = createListQueryStore<Task, TaskFilter, string>({
29
+ id: 'list-query-tasks',
30
+ storeManager,
31
+ fetchListFn: (filter, size, { signal }) => api.getTasks(filter, size, signal),
32
+ fetchItemFn: (taskId, { signal }) => api.getTask(taskId, signal),
33
+ });
34
+ ```
35
+
36
+ The type parameters are:
37
+
38
+ - `ItemState` - The shape of each item
39
+ - `QueryPayload` - The payload that identifies a query (e.g., filter params)
40
+ - `ItemPayload` - The payload that identifies an individual item (e.g., item ID)
41
+ - `TPartialResources` (optional, `boolean`) - Enables [Partial Resources](./partial-resources.md)
42
+ - `TOffsetPagination` (optional, `boolean`) - Enables [Offset Pagination](./offset-pagination.md)
43
+
44
+ ## Options
45
+
46
+ ### Required Options
47
+
48
+ | Option | Type | Description |
49
+ | -------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
50
+ | `id` | `string` | Stable logical store id used for debug labels, persistence namespaces, and tab sync |
51
+ | `storeManager` | `StoreManager` | Shared global config with `getSessionKey`, `errorNormalizer`, and global store controls |
52
+ | `fetchListFn` | Size mode: `(payload, size, options) => Promise<FetchListFnReturn \| Result<FetchListFnReturn, Error>>` | Fetches a paginated list. See [Pagination modes](#pagination-modes) |
53
+
54
+ ### Optional Options
55
+
56
+ | Option | Type | Description |
57
+ | ------------------------------ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
58
+ | `lowPriorityThrottleMs` | `number` | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
59
+ | `baseCoalescingWindowMs` | `number` | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
60
+ | `fetchItemFn` | `(payload, options) => Promise<ItemState \| Result<ItemState, Error>>` | Fetches a single item. Required for `useItem`, `invalidateItem`, `scheduleItemFetch` |
61
+ | `batchFetchItemFn` | `(requests, options) => Promise<Map<ItemPayload, ItemState \| Error \| Result<ItemState, Error>> \| Result<Map>>` | See [Batch Fetching](./batch-fetching.md) |
62
+ | `getItemsBatchKey` | `(payload: ItemPayload) => string \| false` | See [Batch Fetching](./batch-fetching.md) |
63
+ | `defaultQuerySize` | `number` | Default page size (default: `50`) |
64
+ | `maxItemBatchSize` | `number` | Max items per batch fetch. Defaults to `50` |
65
+ | `maxItems` | `number` | Maximum cached items kept in memory. Defaults to `5000`. See [Cache Limits](./cache-limits.md) |
66
+ | `maxQueries` | `number` | Maximum cached queries kept in memory. Defaults to `1000`. See [Cache Limits](./cache-limits.md) |
67
+ | `onStateCleanup` | `(cleanup) => void` | Called when memory cache eviction removes items or queries. See [Cache Limits](./cache-limits.md) |
68
+ | `optimisticListUpdates` | `OptimisticListUpdate[]` | See [Optimistic List Updates](./optimistic-list-updates.md) |
69
+ | `partialResources` | `PartialResourcesConfig` | See [Partial Resources](./partial-resources.md) |
70
+ | `derivedQueries` | `DerivedQueriesConfig` | Derive hook results from local items instead of fetching when possible |
71
+ | `offsetPagination` | `OffsetPaginationConfig` | See [Offset Pagination](./offset-pagination.md) |
72
+ | `getQueryKey` | `(params) => ValidPayload \| unknown[]` | Custom query key derivation |
73
+ | `getItemKey` | `(params) => ValidPayload \| unknown[]` | Custom item key derivation |
74
+ | `mediumPriorityDelayMs` | `number` | Delay before medium-priority fetches execute |
75
+ | `dynamicRealtimeThrottleMs` | `(params) => number` | Overrides the manager default. See [Real-Time Updates](./real-time-updates.md) |
76
+ | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | Refetch on window focus |
77
+ | `transportReconnectCooldownMs` | `number` | Cooldown for repeated transport reconnect revalidation |
78
+ | `usesRealTimeUpdates` | `boolean` | See [Real-Time Updates](./real-time-updates.md) |
79
+ | `onInvalidateQuery` | `(query, priority) => void` | Called when a query is invalidated |
80
+ | `onInvalidateItem` | `(props: { itemState, payload, priority }) => void` | Called when an item is invalidated |
81
+ | `persistentStorage` | `ListQueryPersistentStorageConfig<ItemState, QueryPayload, ItemPayload>` | Configure cache persistence. See [Persistent Storage](./persistent-storage.md) |
82
+ | `onSchedulerEvent` | `(event, data?) => void` | Scheduler event listener |
83
+ | `onMutationError` | `(error, options: { silentErrors?: boolean }) => void` | Global mutation error handler |
84
+
85
+ Fetch callbacks return promises. The resolved value may be either plain data or a `Result`. `Result.ok(data)` is handled as a successful fetch; `Result.err(error)` is normalized into the query or item error state.
86
+
87
+ ### FetchListFnReturn
88
+
89
+ The `fetchListFn` must return:
90
+
91
+ ```ts
92
+ type FetchListFnReturn<ItemState, ItemPayload> = {
93
+ items: { itemPayload: ItemPayload; data: ItemState }[];
94
+ hasMore: boolean;
95
+ };
96
+ ```
97
+
98
+ ### Pagination Modes
99
+
100
+ **Size mode (default):**
101
+
102
+ ```ts
103
+ fetchListFn: (payload, size, { signal, fields? }) => Promise<FetchListFnReturn>
104
+ ```
105
+
106
+ **Offset mode** (when `offsetPagination` is set):
107
+
108
+ ```ts
109
+ fetchListFn: (payload, { offset, limit }, { signal, fields? }) => Promise<FetchListFnReturn>
110
+ ```
111
+
112
+ See [Offset Pagination](./offset-pagination.md) for details.
113
+
114
+ ## State Shape
115
+
116
+ ```ts
117
+ type TSFDListQueryState<ItemState, QueryPayload, ItemPayload> = {
118
+ items: Record<string, ItemState | null>;
119
+ queries: Record<string, TSFDListQuery<QueryPayload>>;
120
+ itemQueries: Record<string, TSDFItemQuery<ItemPayload> | null>;
121
+ itemLoadedFields: Record<string, string[]>;
122
+ itemFieldInvalidationFields: Record<string, string[]>;
123
+ };
124
+ ```
125
+
126
+ ### Query State
127
+
128
+ ```ts
129
+ type TSFDListQuery<QueryPayload> = {
130
+ error: StoreError | null;
131
+ status: 'loading' | 'error' | 'refetching' | 'success' | 'loadingMore';
132
+ payload: QueryPayload;
133
+ hasMore: boolean;
134
+ wasLoaded: boolean;
135
+ refetchOnMount:
136
+ | false
137
+ | 'lowPriority'
138
+ | 'mediumPriority'
139
+ | 'realtimeUpdate'
140
+ | 'highPriority';
141
+ items: string[]; // Array of item keys
142
+ };
143
+ ```
144
+
145
+ ### Item Query State
146
+
147
+ ```ts
148
+ type TSDFItemQuery<ItemPayload> = {
149
+ error: StoreError | null;
150
+ status: 'loading' | 'error' | 'refetching' | 'success';
151
+ wasLoaded: boolean;
152
+ refetchOnMount:
153
+ | false
154
+ | 'lowPriority'
155
+ | 'mediumPriority'
156
+ | 'realtimeUpdate'
157
+ | 'highPriority';
158
+ payload: ItemPayload;
159
+ };
160
+ ```
161
+
162
+ Key points:
163
+
164
+ - `items` stores the actual data, shared across queries
165
+ - `queries` stores query metadata and an ordered list of item keys
166
+ - `itemQueries` stores per-item fetch metadata (for `fetchItemFn`)
167
+ - `itemLoadedFields` / `itemFieldInvalidationFields` are used by [Partial Resources](./partial-resources.md)
168
+ - Derived query results are hook-level computed views only; they are not stored in `queries`
169
+
170
+ ## Derived Queries
171
+
172
+ `derivedQueries` lets hooks resolve a list query from locally materialized items
173
+ instead of fetching when the store can produce a reliable result.
174
+
175
+ ```ts
176
+ derivedQueries: {
177
+ getQueryGroup: (queryPayload) => queryPayload.tableId,
178
+ getItemGroup: (_item, itemPayload) => itemPayload.split('||')[0] ?? '',
179
+ isComplete: (queryPayload, { queries }) => queries.length > 0,
180
+ deriveQuery: (queryPayload, items, { fields, isOfflineMode, deriveSource }) => {
181
+ if (Array.isArray(fields) && fields.includes('age')) {
182
+ return false;
183
+ }
184
+
185
+ return items.map(({ key }) => key);
186
+ },
187
+ }
188
+ ```
189
+
190
+ Behavior:
191
+
192
+ - Online: exact query cache wins; otherwise TSDF can derive when `isComplete(...)` returns `true`
193
+ - Offline: derivation is attempted before the exact cached query result
194
+ - `deriveQuery(...)` receives `{ fields, isOfflineMode, deriveSource }`
195
+ - `fields` lets derivation opt out of partial-resource queries when local data is insufficient
196
+ - `deriveSource` is `'online'`, `'offline'`, or `'sticky-offline'`
197
+ - Derived results expose `isDerived: true`
198
+ - Derived results always expose `hasMore: false`
199
+ - Derived results do not create `state.queries[queryKey]`
200
+
201
+ ## API
202
+
203
+ ### Hooks
204
+
205
+ | Hook | Description | Details |
206
+ | ------------------------------------------- | ------------------------------------------ | ----------------------------------------------------------------------- |
207
+ | `useListQuery(payload, options?)` | Fetch and subscribe to a list query | See [Hooks - useListQuery](./hooks.md#uselistquery) |
208
+ | `usePendingOfflineItems(options?)` | Read queued offline items without fetching | See [Hooks - usePendingOfflineItems](./hooks.md#usependingofflineitems) |
209
+ | `useMultipleListQueries(queries, options?)` | Fetch multiple list queries | See [Hooks - useMultipleListQueries](./hooks.md#usemultiplelistqueries) |
210
+ | `useItem(payload, options?)` | Fetch and subscribe to a single item | See [Hooks - useItem](./hooks.md#useitem) |
211
+ | `useMultipleItems(items, options?)` | Fetch multiple individual items | See [Hooks - useMultipleItems](./hooks.md#usemultipleitems) |
212
+ | `useFindItem(findFn, options?)` | Find an item by predicate across all items | See [Hooks - useFindItem](./hooks.md#usefinditem) |
213
+
214
+ ### Query Methods
215
+
216
+ | Method | Signature | Description |
217
+ | -------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------ |
218
+ | `scheduleListQueryFetch` | `(fetchType, payload(s), size?, options?) => ScheduleFetchResults` | Schedule a list fetch |
219
+ | `awaitListQueryFetch` | `(params, options?) => Promise<{ items, error, hasMore }>` | Await a list fetch |
220
+ | `getQueryFromStateOrFetch` | `(params, options?) => Promise<Result<{ items, hasMore }, StoreFetchError>>` | Return loaded query data or fetch it if missing |
221
+ | `preloadQueryFromStorage` | `(payloads) => Promise<PersistentStoragePreloadResult<QueryPayload>[]>` | Preload cached list query payloads from async storage (OPFS) |
222
+ | `loadMore` | `(params, size?, options?) => ScheduleFetchResults` | Load more items (pagination) |
223
+ | `getQueryState` | `(params) => TSFDListQuery` | Get query state |
224
+ | `getQueryKey` | `(params) => string` | Get composite key for a query payload |
225
+ | `getQueriesState` | `(params) => { query, key }[]` | Get multiple query states |
226
+ | `getQueriesRelatedToItem` | `(itemPayload) => TSFDListQuery[]` | Find queries containing an item |
227
+
228
+ ### Item Methods
229
+
230
+ | Method | Signature | Description |
231
+ | ------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------- |
232
+ | `scheduleItemFetch` | `(fetchType, payload(s), options?) => ScheduleFetchResults` | Schedule an item fetch |
233
+ | `awaitItemFetch` | `(itemPayload, options?) => Promise<{ data, error }>` | Await an item fetch |
234
+ | `getItemFromStateOrFetch` | `(itemPayload, options?) => Promise<Result<ItemState, StoreFetchError>>` | Return loaded item data or fetch it if missing |
235
+ | `preloadItemFromStorage` | `(params) => Promise<PersistentStoragePreloadResult<ItemPayload>[]>` | Preload cached list items from async storage (OPFS) |
236
+ | `getItemKey` | `(params) => string` | Get composite key for an item payload |
237
+ | `getItemState` | `(payload) => ItemState \| null` | Get item data |
238
+
239
+ ### Offline Methods
240
+
241
+ | Method | Description |
242
+ | ----------------------------------------------------- | ----------------------------------------------------------------- |
243
+ | `getOfflineEntities()` / `useOfflineEntities()` | Read offline entities scoped to this store |
244
+ | `getOfflineResolutions()` / `useOfflineResolutions()` | Read manual conflict/retry resolutions scoped to this store |
245
+ | `parseOfflineResolutionConflict(resolution)` | Narrow a persisted resolution to this store's operation types |
246
+ | `resolveOfflineResolution(id, operation, action)` | Resolve, retry, discard, requeue, or commit an offline resolution |
247
+
248
+ ### Offline Queue Hook
249
+
250
+ `usePendingOfflineItems(options?)` is the list-query-store hook for reading the
251
+ store's pending offline item state directly.
252
+
253
+ Use it when:
254
+
255
+ - you need queued offline items even if no query is mounted
256
+ - you want pending deletes separately from visible pending items
257
+ - you want offline queue UI without triggering fetches
258
+
259
+ Unlike `useListQuery(...)`, it does not load query results or expose query
260
+ status. It derives data from the offline queue, overlays, live store state,
261
+ and persisted item snapshots, using the precomputed offline entity lifecycle
262
+ kind so pending deletes do not need item hydration before they appear.
263
+
264
+ ### Mutation Methods
265
+
266
+ | Method | Description | Details |
267
+ | ----------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------- |
268
+ | `invalidateQueryAndItems(options)` | Invalidate queries and/or items | See [Invalidation](./invalidation.md) |
269
+ | `invalidateItem(payload(s), priority?)` | Invalidate item(s) only | See [Invalidation](./invalidation.md) |
270
+ | `updateItemState(itemIds, produceFn, options?)` | Immer-based item update + applies [Optimistic List Updates](./optimistic-list-updates.md) |
271
+ | `addItemToState(itemPayload, data, options?)` | Add an item with optional query placement |
272
+ | `deleteItemState(itemId)` | Delete item from all queries |
273
+ | `startItemMutation(itemId)` | Start mutation lock on item + related queries |
274
+ | `performMutation(payload, options)` | Full mutation lifecycle. See [Mutations](./mutations.md) |
275
+
276
+ ### Other
277
+
278
+ | Method | Description |
279
+ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
280
+ | `reset()` | Full reset of all state and schedulers |
281
+ | `onTransportReconnect()` | Store-level reconnect hook. Prefer `storeManager.onTransportReconnect()` for shared transports. See [Real-Time Updates](./real-time-updates.md) |
282
+
283
+ ### Properties
284
+
285
+ | Property | Type | Description |
286
+ | ------------- | ------------------------------------ | --------------------------------------------------------- |
287
+ | `store` | `Store<TSFDListQueryState>` | Underlying t-state store |
288
+ | `events` | `Emitter<ListQueryStoreEvents>` | Invalidation events (`invalidateQuery`, `invalidateItem`) |
289
+ | `storeEvents` | `Emitter<ListQueryStoreStoreEvents>` | Mutation lifecycle events |
290
+
291
+ ## Usage Example
292
+
293
+ ```tsx
294
+ // List view
295
+ function TaskList({ projectId }: { projectId: string }) {
296
+ const { items, isLoading, hasMore, status } = taskStore.useListQuery({
297
+ projectId,
298
+ status: 'todo',
299
+ });
300
+
301
+ if (isLoading) return <Spinner />;
302
+
303
+ return (
304
+ <div>
305
+ {items.map((task) => (
306
+ <TaskRow
307
+ key={task.id}
308
+ task={task}
309
+ />
310
+ ))}
311
+ {hasMore && (
312
+ <button
313
+ onClick={() => taskStore.loadMore({ projectId, status: 'todo' })}
314
+ >
315
+ Load More
316
+ </button>
317
+ )}
318
+ </div>
319
+ );
320
+ }
321
+
322
+ // Item view (shares state with list)
323
+ function TaskDetail({ taskId }: { taskId: string }) {
324
+ const { data, isLoading } = taskStore.useItem(taskId);
325
+
326
+ if (isLoading) return <Spinner />;
327
+
328
+ return <div>{data?.title}</div>;
329
+ }
330
+
331
+ // Add item to specific queries
332
+ taskStore.addItemToState('task-new', newTask, {
333
+ addItemToQueries: {
334
+ queries: { projectId: 'proj-1', status: 'todo' },
335
+ appendTo: 'start',
336
+ },
337
+ });
338
+ ```
339
+
340
+ ## addItemToState Options
341
+
342
+ ```ts
343
+ addItemToState(itemPayload, data, {
344
+ addItemToQueries?: {
345
+ queries: QueryPayload[] | FilterQuery | QueryPayload;
346
+ appendTo: 'start' | 'end' | ((itemsPayload: ItemPayload[]) => number);
347
+ }
348
+ })
349
+ ```
350
+
351
+ - `queries` - Which queries to add the item to
352
+ - `appendTo` - Where to insert: `'start'`, `'end'`, or a function returning the insertion index