@osdk/react 2.94.0 → 2.95.0-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a

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 (64) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/build/browser/new/platform-apis/admin/useCurrentFoundryUser.js.map +1 -1
  3. package/build/browser/new/platform-apis/admin/useFoundryUser.js.map +1 -1
  4. package/build/browser/new/platform-apis/admin/useFoundryUsersList.js.map +1 -1
  5. package/build/browser/new/useLinks.js.map +1 -1
  6. package/build/browser/new/useObjectSet.js.map +1 -1
  7. package/build/browser/new/useOsdkAggregation.js +2 -5
  8. package/build/browser/new/useOsdkAggregation.js.map +1 -1
  9. package/build/browser/new/useOsdkObjects.js.map +1 -1
  10. package/build/browser/util/UserAgent.js +1 -1
  11. package/build/browser/util/UserAgent.js.map +1 -1
  12. package/build/cjs/{chunk-EJT5W6SI.cjs → chunk-YG7PT4LT.cjs} +3 -3
  13. package/build/cjs/chunk-YG7PT4LT.cjs.map +1 -0
  14. package/build/cjs/index.cjs +15 -15
  15. package/build/cjs/public/experimental.cjs +16 -16
  16. package/build/cjs/public/experimental.d.cts +9 -12
  17. package/build/cjs/public/platform-apis.d.cts +1 -4
  18. package/build/esm/new/platform-apis/admin/useCurrentFoundryUser.js.map +1 -1
  19. package/build/esm/new/platform-apis/admin/useFoundryUser.js.map +1 -1
  20. package/build/esm/new/platform-apis/admin/useFoundryUsersList.js.map +1 -1
  21. package/build/esm/new/useLinks.js.map +1 -1
  22. package/build/esm/new/useObjectSet.js.map +1 -1
  23. package/build/esm/new/useOsdkAggregation.js +2 -5
  24. package/build/esm/new/useOsdkAggregation.js.map +1 -1
  25. package/build/esm/new/useOsdkObjects.js.map +1 -1
  26. package/build/esm/util/UserAgent.js +1 -1
  27. package/build/esm/util/UserAgent.js.map +1 -1
  28. package/build/types/new/platform-apis/admin/useCurrentFoundryUser.d.ts +0 -1
  29. package/build/types/new/platform-apis/admin/useCurrentFoundryUser.d.ts.map +1 -1
  30. package/build/types/new/platform-apis/admin/useFoundryUser.d.ts +1 -2
  31. package/build/types/new/platform-apis/admin/useFoundryUser.d.ts.map +1 -1
  32. package/build/types/new/platform-apis/admin/useFoundryUsersList.d.ts +0 -1
  33. package/build/types/new/platform-apis/admin/useFoundryUsersList.d.ts.map +1 -1
  34. package/build/types/new/useLinks.d.ts +2 -2
  35. package/build/types/new/useObjectSet.d.ts +2 -2
  36. package/build/types/new/useOsdkAggregation.d.ts +3 -6
  37. package/build/types/new/useOsdkAggregation.d.ts.map +1 -1
  38. package/build/types/new/useOsdkObjects.d.ts +2 -2
  39. package/docs/actions.mdx +314 -0
  40. package/docs/aggregations.mdx +256 -0
  41. package/docs/cache-invalidation.mdx +229 -0
  42. package/docs/devtools/cache.mdx +29 -0
  43. package/docs/devtools/components.mdx +40 -0
  44. package/docs/devtools/console.mdx +29 -0
  45. package/docs/devtools/index.mdx +151 -0
  46. package/docs/devtools/overview.mdx +45 -0
  47. package/docs/functions.mdx +246 -0
  48. package/docs/index.mdx +62 -0
  49. package/docs/links.mdx +270 -0
  50. package/docs/meta.json +30 -0
  51. package/docs/object-sets.mdx +296 -0
  52. package/docs/objects.mdx +489 -0
  53. package/docs/optimistic-updates.mdx +164 -0
  54. package/docs/platform-apis.mdx +296 -0
  55. package/docs/testing.mdx +348 -0
  56. package/package.json +7 -7
  57. package/build/cjs/chunk-EJT5W6SI.cjs.map +0 -1
  58. package/docs/actions.md +0 -432
  59. package/docs/advanced-queries.md +0 -678
  60. package/docs/cache-management.md +0 -222
  61. package/docs/getting-started.md +0 -319
  62. package/docs/platform-apis.md +0 -234
  63. package/docs/prerequisites.md +0 -48
  64. package/docs/querying-data.md +0 -810
@@ -1,810 +0,0 @@
1
- ---
2
- sidebar_position: 2
3
- ---
4
-
5
- # Querying Data
6
-
7
- This guide covers all the ways to fetch data from the server using OSDK React hooks.
8
-
9
- ## useOsdkObjects
10
-
11
- Retrieve and observe collections of objects with automatic cache management.
12
-
13
- ### Basic Usage
14
-
15
- ```tsx
16
- import { Todo } from "@my/osdk";
17
- import { type UseOsdkListResult, useOsdkObjects } from "@osdk/react";
18
-
19
- function TodoList() {
20
- const {
21
- data,
22
- isLoading,
23
- isOptimistic,
24
- error,
25
- fetchMore,
26
- }: UseOsdkListResult<typeof Todo> = useOsdkObjects(Todo);
27
-
28
- if (!data && isLoading) {
29
- return "Loading...";
30
- }
31
-
32
- return (
33
- <div>
34
- {isLoading && <div>Refreshing data</div>}
35
- {data.map(todo => <TodoView key={todo.$primaryKey} todo={todo} />)}
36
- </div>
37
- );
38
- }
39
- ```
40
-
41
- ### Return Values
42
-
43
- - `data` — Array of objects matching the query (undefined while initially loading)
44
- - `isLoading` — True while fetching data from server (can be true while `data` exists during revalidation)
45
- - `isOptimistic` — True if the list order is affected by optimistic updates (see note below)
46
- - `fetchMore` — Function to load next page (undefined when no more pages available)
47
- - `hasMore` — True if more pages can be fetched
48
- - `totalCount` — Total count of matching objects when available from the API. Returned as a string; parse with `Number(totalCount)` if you need arithmetic
49
- - `objectSet` — The transformed `ObjectSet` after pivots / set ops; useful as input to a subsequent `useObjectSet` or `useOsdkAggregation`
50
- - `refetch` — Function to manually invalidate this object type and refetch
51
- - `error` — Error object if fetch failed
52
-
53
- :::note About isOptimistic
54
- `isOptimistic` refers to whether the **ordered list of objects** (considering only primary keys) is optimistic. To check if individual object contents are optimistic, use `useOsdkObject` on each object.
55
- :::
56
-
57
- ### Fetching by RID
58
-
59
- Fetch specific objects by their RIDs:
60
-
61
- ```tsx
62
- import { Employee } from "@my/osdk";
63
- import { useOsdkObjects } from "@osdk/react";
64
-
65
- function SelectedEmployees({ selectedRids }: { selectedRids: string[] }) {
66
- const { data, isLoading } = useOsdkObjects(Employee, {
67
- rids: selectedRids,
68
- });
69
-
70
- if (isLoading && !data) {
71
- return <div>Loading selected employees...</div>;
72
- }
73
-
74
- return (
75
- <div>
76
- {data?.map(employee => (
77
- <div key={employee.$primaryKey}>{employee.fullName}</div>
78
- ))}
79
- </div>
80
- );
81
- }
82
- ```
83
-
84
- ### Filtering with `where`
85
-
86
- ```ts
87
- const { data, isLoading } = useOsdkObjects(Todo, {
88
- where: { text: { $startsWith: "cool " } },
89
- });
90
- ```
91
-
92
- ### Text Search Filters
93
-
94
- OSDK provides several text search operators for string properties. Understanding the differences helps you choose the right one for your use case.
95
-
96
- #### `$startsWith`
97
-
98
- Matches strings that begin with the specified prefix.
99
-
100
- ```ts
101
- const { data } = useOsdkObjects(Employee, {
102
- where: { fullName: { $startsWith: "John" } },
103
- });
104
- // Matches: "John Smith", "Johnny Appleseed"
105
- // Does NOT match: "Mary Johnson"
106
- ```
107
-
108
- #### `$containsAnyTerm`
109
-
110
- Matches if the property contains **any** of the search terms. Terms are space-separated. Useful for broad searches where matching any word is sufficient.
111
-
112
- ```ts
113
- const { data } = useOsdkObjects(Article, {
114
- where: { content: { $containsAnyTerm: "react typescript javascript" } },
115
- });
116
- // Matches articles containing "react" OR "typescript" OR "javascript"
117
- ```
118
-
119
- With fuzzy matching enabled, minor typos are tolerated:
120
-
121
- ```ts
122
- const { data } = useOsdkObjects(Article, {
123
- where: {
124
- content: { $containsAnyTerm: { term: "react", fuzzySearch: true } },
125
- },
126
- });
127
- // Fuzzy matching handles common typos automatically
128
- ```
129
-
130
- #### `$containsAllTerms`
131
-
132
- Matches if the property contains **all** of the search terms, in any order. Use this for more precise searches where all keywords must be present.
133
-
134
- ```ts
135
- const { data } = useOsdkObjects(Article, {
136
- where: { content: { $containsAllTerms: "react hooks tutorial" } },
137
- });
138
- // Matches: "This tutorial covers React hooks in depth"
139
- // Matches: "Learn hooks - a React tutorial"
140
- // Does NOT match: "React components guide" (missing "hooks" and "tutorial")
141
- ```
142
-
143
- With fuzzy matching:
144
-
145
- ```ts
146
- const { data } = useOsdkObjects(Article, {
147
- where: {
148
- content: { $containsAllTerms: { term: "react hooks", fuzzySearch: true } },
149
- },
150
- });
151
- ```
152
-
153
- #### `$containsAllTermsInOrder`
154
-
155
- Matches if the property contains all terms **in the exact order specified**. Use this for phrase matching.
156
-
157
- ```ts
158
- const { data } = useOsdkObjects(Document, {
159
- where: { title: { $containsAllTermsInOrder: "quarterly sales report" } },
160
- });
161
- // Matches: "Q4 Quarterly Sales Report 2024"
162
- // Does NOT match: "Sales Report - Quarterly" (wrong order)
163
- ```
164
-
165
- #### Search Filter Comparison
166
-
167
- | Filter | Match Requirement | Fuzzy | Phonetic | Use Case |
168
- | -------------------------- | ----------------------------- | ----- | -------- | ---------------------------- |
169
- | `$startsWith` | Begins with prefix | no | yes | Autocomplete, prefix search |
170
- | `$containsAnyTerm` | Any term present | yes | yes | Broad keyword search |
171
- | `$containsAllTerms` | All terms present (any order) | yes | yes | Precise multi-keyword search |
172
- | `$containsAllTermsInOrder` | All terms in exact order | no | yes | Phrase / exact match search |
173
-
174
- Fuzzy search is unavailable for `$containsAllTermsInOrder` because phrase matching requires exact token order.
175
-
176
- All four text search filters support phonetic matching when the property is configured for phonetic search:
177
-
178
- ```ts
179
- const { data } = useOsdkObjects(Employee, {
180
- where: {
181
- fullName: {
182
- $containsAnyTerm: { term: "Jon", phoneticSearch: true },
183
- },
184
- },
185
- });
186
- // Can match similarly pronounced values such as "Jon" and "John"
187
- ```
188
-
189
- `phoneticSearch: true` cannot be combined with `fuzzySearch: true` in the same filter. Use an `$or` clause with separate fuzzy and phonetic filters when both matching strategies are needed.
190
-
191
- #### Search Example: Building a Search Box
192
-
193
- ```tsx
194
- import { Article } from "@my/osdk";
195
- import { useOsdkObjects } from "@osdk/react";
196
- import { useState } from "react";
197
-
198
- function ArticleSearch() {
199
- const [searchQuery, setSearchQuery] = useState("");
200
-
201
- const { data, isLoading } = useOsdkObjects(Article, {
202
- where: searchQuery
203
- ? {
204
- title: { $containsAnyTerm: { term: searchQuery, fuzzySearch: true } },
205
- }
206
- : undefined,
207
- enabled: searchQuery.length >= 2,
208
- });
209
-
210
- return (
211
- <div>
212
- <input
213
- type="text"
214
- placeholder="Search articles..."
215
- value={searchQuery}
216
- onChange={e => setSearchQuery(e.target.value)}
217
- />
218
-
219
- {isLoading && <div>Searching...</div>}
220
-
221
- {data?.map(article => <div key={article.$primaryKey}>{article.title}
222
- </div>)}
223
- </div>
224
- );
225
- }
226
- ```
227
-
228
- ### Sorting with `orderBy`
229
-
230
- ```ts
231
- const { data } = useOsdkObjects(Todo, {
232
- orderBy: { createdAt: "desc" },
233
- });
234
- ```
235
-
236
- ### Selecting Properties with `$select`
237
-
238
- Without `$select`, the API loads its default property set (vector properties, for example, are not included). Pass `$select` with only the properties your component reads (the primary key is always returned):
239
-
240
- ```tsx
241
- const { data } = useOsdkObjects(Todo, {
242
- $select: ["title", "isComplete"],
243
- });
244
- ```
245
-
246
- Loading unused properties wastes bandwidth and compute and can slow down retrieval, and reading fewer properties afterwards does not avoid the cost of fetching them. Unlike `fetchPage` and `asyncIter`, `useOsdkObjects` does not narrow the returned type to the selected properties: reading a property you didn't select still type-checks, but is `undefined` at runtime. Keep `$select` in sync with the properties your component reads.
247
-
248
- ### Pagination
249
-
250
- Control page size and load more results:
251
-
252
- ```tsx
253
- function TodoList() {
254
- const { data, isLoading, fetchMore } = useOsdkObjects(Todo, {
255
- pageSize: 10,
256
- });
257
-
258
- return (
259
- <div>
260
- {data?.map(todo => <TodoView key={todo.$primaryKey} todo={todo} />)}
261
-
262
- {fetchMore && (
263
- <button onClick={() => fetchMore()} disabled={isLoading}>
264
- {isLoading ? "Loading..." : "Load More"}
265
- </button>
266
- )}
267
- </div>
268
- );
269
- }
270
- ```
271
-
272
- `pageSize` is the size of one page, not a limit on the total number of objects.
273
-
274
- :::note Paging consistency
275
- Pages are loaded without a snapshot. If objects are added, removed, or edited between page loads, later pages may repeat or skip objects. When you need every object from one consistent view outside of a component, use `asyncIter()` on the client (see [useOsdkClient](#useosdkclient)).
276
- :::
277
-
278
- ### Auto-Fetching Pages
279
-
280
- By default, only the first page is fetched. Use `autoFetchMore` to load more automatically:
281
-
282
- ```tsx
283
- // Fetch all pages automatically
284
- const { data, isLoading } = useOsdkObjects(Todo, {
285
- autoFetchMore: true,
286
- });
287
-
288
- // Fetch at least 100 items
289
- const { data, isLoading, fetchMore } = useOsdkObjects(Todo, {
290
- autoFetchMore: 100,
291
- pageSize: 25, // Will load 4 pages
292
- });
293
- ```
294
-
295
- :::warning Performance Warning
296
- Using `autoFetchMore: true` on large datasets may cause long load times and high memory usage. Prefer `autoFetchMore: N` with a specific number, or `fetchMore` on demand: a UI can only show so much at once. For counts, sums, or group-bys, use [`useOsdkAggregation`](./advanced-queries.md#useosdkaggregation) instead of loading objects.
297
- :::
298
-
299
- ### Conditional Queries with `enabled`
300
-
301
- Control when a query executes:
302
-
303
- ```tsx
304
- import { Todo } from "@my/osdk";
305
- import { useOsdkObjects } from "@osdk/react";
306
- import { useState } from "react";
307
-
308
- function ConditionalTodoFetch() {
309
- const [shouldFetch, setShouldFetch] = useState(false);
310
-
311
- const { data, isLoading } = useOsdkObjects(Todo, {
312
- where: { isComplete: false },
313
- enabled: shouldFetch, // Only fetch when true
314
- });
315
-
316
- return (
317
- <div>
318
- <button onClick={() => setShouldFetch(!shouldFetch)}>
319
- {shouldFetch ? "Hide" : "Show"} Incomplete Todos
320
- </button>
321
-
322
- {shouldFetch && isLoading && !data && <div>Loading...</div>}
323
- {data?.map(todo => <div key={todo.$primaryKey}>{todo.title}</div>)}
324
- </div>
325
- );
326
- }
327
- ```
328
-
329
- ### Real-time Updates with `streamUpdates`
330
-
331
- Enable WebSocket-based real-time updates:
332
-
333
- ```tsx
334
- import { Todo } from "@my/osdk";
335
- import { useOsdkObjects } from "@osdk/react";
336
-
337
- function LiveTodoList() {
338
- const { data, isLoading } = useOsdkObjects(Todo, {
339
- where: { isComplete: false },
340
- orderBy: { createdAt: "desc" },
341
- streamUpdates: true,
342
- });
343
-
344
- // Data automatically updates when:
345
- // - New todos matching the where clause are created
346
- // - Existing todos are modified and still match
347
- // - Todos are deleted or no longer match
348
-
349
- if (isLoading && !data) {
350
- return <div>Loading todos...</div>;
351
- }
352
-
353
- return (
354
- <div>
355
- <h2>Live Todo List ({data?.length})</h2>
356
- {data?.map(todo => (
357
- <div key={todo.$primaryKey}>
358
- <span>{todo.title}</span>
359
- {isLoading && (
360
- <span style={{ fontSize: "0.8em" }}>
361
- (Updating...)
362
- </span>
363
- )}
364
- </div>
365
- ))}
366
- </div>
367
- );
368
- }
369
- ```
370
-
371
- :::note Limitations
372
- `streamUpdates` cannot be used together with `pivotTo` or `withProperties`. The server does not support websocket subscriptions for link-traversal or derived-property queries. Those queries still fetch data normally but won't receive real-time updates.
373
- :::
374
-
375
- ### Set Intersections with `intersectWith`
376
-
377
- Find objects matching multiple where clauses:
378
-
379
- ```tsx
380
- import { Employee } from "@my/osdk";
381
- import { useOsdkObjects } from "@osdk/react";
382
-
383
- function EmployeesIntersection() {
384
- const { data, isLoading } = useOsdkObjects(Employee, {
385
- where: { department: "Engineering" },
386
- intersectWith: [
387
- { where: { salary: { $gte: 100000 } } },
388
- { where: { yearsExperience: { $gte: 5 } } },
389
- ],
390
- orderBy: { fullName: "asc" },
391
- });
392
-
393
- if (isLoading && !data) {
394
- return <div>Loading...</div>;
395
- }
396
-
397
- return (
398
- <div>
399
- <h3>Senior Engineers with High Salary ({data?.length})</h3>
400
- {data?.map(employee => (
401
- <div key={employee.$primaryKey}>{employee.fullName}</div>
402
- ))}
403
- </div>
404
- );
405
- }
406
- ```
407
-
408
- ### Pivot to Related Objects with `pivotTo`
409
-
410
- Traverse relationships and return linked objects:
411
-
412
- ```tsx
413
- import { Employee } from "@my/osdk";
414
- import { useOsdkObjects } from "@osdk/react";
415
-
416
- function ManagerReports() {
417
- const { data, isLoading } = useOsdkObjects(Employee, {
418
- where: { fullName: "John Smith" },
419
- pivotTo: "reports", // Changes return type from Employee[] to Report[]
420
- });
421
-
422
- if (isLoading && !data) {
423
- return <div>Loading...</div>;
424
- }
425
-
426
- return (
427
- <div>
428
- <h3>John Smith's Direct Reports ({data?.length})</h3>
429
- {data?.map(report => <div key={report.$primaryKey}>{report.fullName}
430
- </div>)}
431
- </div>
432
- );
433
- }
434
- ```
435
-
436
- ### All Options
437
-
438
- ```ts
439
- const result = useOsdkObjects(Todo, {
440
- rids: [
441
- "ri.phonograph2-objects.main.object.abc123",
442
- "ri.phonograph2-objects.main.object.def456",
443
- ],
444
- where: { isComplete: false },
445
- pageSize: 20,
446
- orderBy: { createdAt: "desc" },
447
- dedupeIntervalMs: 5000,
448
- streamUpdates: true,
449
- autoFetchMore: 100,
450
- enabled: true,
451
- intersectWith: [{ where: { priority: "high" } }],
452
- $select: ["title", "isComplete"],
453
- $loadPropertySecurityMetadata: true,
454
- withProperties: {
455
- /* see /react/advanced-queries#derived-properties */
456
- },
457
- });
458
- ```
459
-
460
- `streamUpdates` and `pivotTo` cannot be combined — see the note above.
461
-
462
- :::note
463
- `streamUpdates` and `pivotTo` cannot be used together. The server does not support
464
- websocket subscriptions for link-traversal queries. Queries using `pivotTo` will
465
- still fetch data normally but won't receive real-time updates.
466
- :::
467
-
468
- ---
469
-
470
- ## useOsdkObject
471
-
472
- Retrieve and observe a single object.
473
-
474
- ### Tracking an Existing Instance
475
-
476
- Pass an object instance to track its loading and optimistic state:
477
-
478
- ```tsx
479
- import { Todo } from "@my/osdk";
480
- import { useOsdkObject } from "@osdk/react";
481
-
482
- function TodoView({ todo }: { todo: Todo.OsdkInstance }) {
483
- const { object, isLoading, isOptimistic, error } = useOsdkObject(todo);
484
-
485
- return (
486
- <div>
487
- {object?.title || todo.title}
488
- {isLoading && " (Loading)"}
489
- {isOptimistic && " (Optimistic)"}
490
- {error && <div>Error: {error.message}</div>}
491
- </div>
492
- );
493
- }
494
- ```
495
-
496
- ### Loading by Primary Key
497
-
498
- Fetch an object by its type and primary key:
499
-
500
- ```tsx
501
- import { Todo } from "@my/osdk";
502
- import { useOsdkObject } from "@osdk/react";
503
-
504
- function TodoLoader({ todoId }: { todoId: string }) {
505
- const { object, isLoading, error } = useOsdkObject(Todo, todoId);
506
-
507
- if (isLoading && !object) {
508
- return <div>Loading todo...</div>;
509
- }
510
-
511
- if (error) {
512
- return <div>Error loading todo: {error.message}</div>;
513
- }
514
-
515
- if (!object) {
516
- return <div>Todo not found</div>;
517
- }
518
-
519
- return <TodoView todo={object} />;
520
- }
521
- ```
522
-
523
- ### Loading with options
524
-
525
- A third argument lets you restrict properties or load per-property security metadata:
526
-
527
- ```tsx
528
- const { object } = useOsdkObject(Todo, todoId, {
529
- $select: ["title", "isComplete"],
530
- $loadPropertySecurityMetadata: true,
531
- });
532
- ```
533
-
534
- Or pass a boolean to disable the query:
535
-
536
- ```tsx
537
- const { object } = useOsdkObject(Todo, todoId, false);
538
- ```
539
-
540
- ### Return Values
541
-
542
- - `object` — The object instance (may be undefined while loading)
543
- - `isLoading` — True while fetching from server
544
- - `isOptimistic` — True if object has optimistic updates applied
545
- - `error` — Error object if fetch failed (cleared once a fresh successful fetch lands)
546
-
547
- ---
548
-
549
- ## useLinks
550
-
551
- Observe and navigate relationships between objects.
552
-
553
- ### Basic Usage
554
-
555
- ```tsx
556
- import { Employee } from "@my/osdk";
557
- import { useLinks } from "@osdk/react";
558
-
559
- function EmployeeReports({ employee }: { employee: Employee.OsdkInstance }) {
560
- const { links, isLoading, fetchMore, hasMore } = useLinks(
561
- employee,
562
- "reports",
563
- {
564
- pageSize: 10,
565
- orderBy: { name: "asc" },
566
- where: { isActive: true },
567
- },
568
- );
569
-
570
- if (isLoading && !links) {
571
- return <div>Loading reports...</div>;
572
- }
573
-
574
- return (
575
- <div>
576
- <h3>Reports ({links?.length})</h3>
577
- {links?.map(report => <div key={report.$primaryKey}>{report.name}</div>)}
578
-
579
- {hasMore && (
580
- <button onClick={() => fetchMore?.()} disabled={isLoading}>
581
- Load More
582
- </button>
583
- )}
584
- </div>
585
- );
586
- }
587
- ```
588
-
589
- ### Multiple Source Objects
590
-
591
- Load links from multiple objects at once:
592
-
593
- ```tsx
594
- function TeamMembers({ employees }: { employees: Employee.OsdkInstance[] }) {
595
- const { links, isLoading } = useLinks(employees, "reports");
596
-
597
- return (
598
- <div>
599
- <h3>All Team Reports</h3>
600
- {links?.map(report => <div key={report.$primaryKey}>{report.name}</div>)}
601
- </div>
602
- );
603
- }
604
- ```
605
-
606
- ### Lazy Loading with `enabled`
607
-
608
- ```tsx
609
- import { Employee } from "@my/osdk";
610
- import { useLinks } from "@osdk/react";
611
- import { useState } from "react";
612
-
613
- function OptionalReportsList(
614
- { employee }: { employee: Employee.OsdkInstance },
615
- ) {
616
- const [showReports, setShowReports] = useState(false);
617
-
618
- const { links, isLoading } = useLinks(employee, "reports", {
619
- enabled: showReports,
620
- });
621
-
622
- return (
623
- <div>
624
- <button onClick={() => setShowReports(!showReports)}>
625
- {showReports ? "Hide" : "Show"} Reports
626
- </button>
627
-
628
- {showReports && isLoading && !links && <div>Loading...</div>}
629
- {links?.map(report => <div key={report.$primaryKey}>{report.name}</div>)}
630
- </div>
631
- );
632
- }
633
- ```
634
-
635
- Set `autoFetchMore: true` to load all pages of linked objects, or set a number to load at least that many linked objects per source. When omitted or `false`, use `fetchMore()` to load additional pages.
636
-
637
- ```ts
638
- const { links, isLoading } = useLinks(employee, "reports", {
639
- pageSize: 20,
640
- autoFetchMore: 100,
641
- });
642
- ```
643
-
644
- ### Controlling Re-fetch Behavior
645
-
646
- By default, `useLinks` deduplicates network requests within a 2-second window. You can customize this with `dedupeIntervalMs`:
647
-
648
- ```tsx
649
- const { links } = useLinks(employee, "reports", {
650
- dedupeIntervalMs: 10000, // don't re-fetch within 10 seconds
651
- });
652
- ```
653
-
654
- To prevent re-fetching entirely on remount and only refresh when the server data is invalidated (e.g. after an action), use `Infinity`:
655
-
656
- ```tsx
657
- const { links } = useLinks(employee, "reports", {
658
- dedupeIntervalMs: Infinity,
659
- });
660
- ```
661
-
662
- ### Options
663
-
664
- - `where` - Filter linked objects
665
- - `pageSize` - Number of links per page
666
- - `autoFetchMore` - Load all pages (`true`) or at least the given number of linked objects per source
667
- - `orderBy` - Sort order for linked objects
668
- - `mode` - Fetch mode: `"force"` (always fetch), `"offline"` (cache only), or undefined (default)
669
- - `dedupeIntervalMs` - Minimum time between re-fetches (default: 2000ms)
670
- - `enabled` - Enable/disable the query (default: true)
671
-
672
- ### Return Values
673
-
674
- - `links` - Array of linked objects
675
- - `isLoading` - True while fetching
676
- - `isOptimistic` - True if links affected by optimistic updates
677
- - `fetchMore` - Function to load next page
678
- - `hasMore` - True if more pages available
679
- - `error` - Error object if fetch failed
680
-
681
- ---
682
-
683
- ## useOsdkClient
684
-
685
- _Stable - available from both `@osdk/react` and `@osdk/react/experimental`_
686
-
687
- Access the OSDK client directly for custom queries.
688
-
689
- ```tsx
690
- import { Todo } from "@my/osdk";
691
- import { useOsdkClient } from "@osdk/react";
692
-
693
- function MyComponent() {
694
- const client = useOsdkClient();
695
-
696
- const loadTodos = async () => {
697
- const todos = await client(Todo).fetchPage({
698
- $select: ["title", "isComplete"],
699
- $pageSize: 50,
700
- });
701
- // ...
702
- };
703
-
704
- return <button onClick={loadTodos}>Load Todos</button>;
705
- }
706
- ```
707
-
708
- Use this when you need to perform queries outside the reactive hook system, such as in event handlers or effects where you manage state manually.
709
-
710
- ### Loading pages vs. loading everything
711
-
712
- | Method | Loads | Snapshot |
713
- | -------------------------- | --------------------------------------- | --------------------------------------------------- |
714
- | `fetchPage({ $pageSize })` | One page; continue with `nextPageToken` | Only with `$snapshot: true` (pass it on every page) |
715
- | `asyncIter()` | Every matching object, page after page | Always |
716
- | `aggregate({ ... })` | Counts, sums, and group-bys only | n/a |
717
-
718
- Without a snapshot, later pages may repeat or skip objects if the data changes between requests. A snapshot configured for a function run still applies regardless of the method. With a snapshot, every page of a non-stream-backed object type reflects the same point in time, so a completed traversal returns each object exactly once. Paging fails if the snapshot expires or the backend detects a paging inconsistency (`PagingInconsistencyDetected`). Stream-backed object types do not provide this snapshot guarantee across pages: changes during a traversal can cause it to fail, and exactly-once traversal is not guaranteed.
719
-
720
- If a full `asyncIter()` traversal of a frequently updated object type fails, aggregate instead if you only need a summary, `$select` fewer properties and filter the object set so the traversal finishes sooner, or loop over `fetchPage()` yourself and de-duplicate by `$primaryKey`. Without a snapshot, de-duplication removes repeated objects but does not recover skipped ones.
721
-
722
- Both `fetchPage` and `asyncIter` load the API's default property set unless you pass `$select`. With `asyncIter`, handle each object as it arrives rather than collecting all of them into an array:
723
-
724
- ```ts
725
- // ✗ Loads the default property set for every object and holds all of them in memory
726
- const todos = await Array.fromAsync(client(Todo).asyncIter());
727
-
728
- // ✓ Loads only the property that is used, one object at a time
729
- let completed = 0;
730
- for await (const todo of client(Todo).asyncIter({ $select: ["isComplete"] })) {
731
- if (todo.isComplete) completed++;
732
- }
733
-
734
- // ✓✓ Better still for counts: aggregate on the server without loading any objects
735
- const { $count } = await client(Todo)
736
- .where({ isComplete: true })
737
- .aggregate({ $select: { $count: "unordered" } });
738
- ```
739
-
740
- ---
741
-
742
- ## Error Handling
743
-
744
- All hooks return an `error` field. A basic pattern:
745
-
746
- ```tsx
747
- import { Todo } from "@my/osdk";
748
- import { useOsdkObjects } from "@osdk/react";
749
-
750
- function TodoList() {
751
- const { data, isLoading, error } = useOsdkObjects(Todo);
752
-
753
- if (error) {
754
- return (
755
- <div>
756
- <h2>Error loading todos</h2>
757
- <p>{JSON.stringify(error)}</p>
758
- <button onClick={() => window.location.reload()}>Retry</button>
759
- </div>
760
- );
761
- }
762
-
763
- if (isLoading && !data) {
764
- return <div>Loading todos...</div>;
765
- }
766
-
767
- return (
768
- <div>
769
- {data?.map(todo => <TodoView key={todo.$primaryKey} todo={todo} />)}
770
- </div>
771
- );
772
- }
773
- ```
774
-
775
- ---
776
-
777
- ## Combining Multiple Hooks
778
-
779
- A common pattern is using multiple hooks together:
780
-
781
- ```tsx
782
- import { Todo } from "@my/osdk";
783
- import { useLinks, useOsdkObject } from "@osdk/react";
784
-
785
- function TodoWithDetails({ todoId }: { todoId: string }) {
786
- const { object: todo, isLoading: todoLoading } = useOsdkObject(Todo, todoId);
787
-
788
- const { links: comments, isLoading: commentsLoading } = useLinks(
789
- todo,
790
- "comments",
791
- { orderBy: { createdAt: "desc" } },
792
- );
793
-
794
- if (todoLoading) return <div>Loading...</div>;
795
- if (!todo) return <div>Todo not found</div>;
796
-
797
- return (
798
- <div>
799
- <h2>{todo.title}</h2>
800
- <p>{todo.description}</p>
801
-
802
- <h3>Comments ({comments?.length || 0})</h3>
803
- {commentsLoading && <div>Loading comments...</div>}
804
- {comments?.map(comment => (
805
- <div key={comment.$primaryKey}>{comment.text}</div>
806
- ))}
807
- </div>
808
- );
809
- }
810
- ```