@osdk/react 2.94.0 → 2.94.1-main-718be7c10524d5aa3086fbfd38785c0abd0a2c87

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 +9 -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-4PFYL4UI.cjs} +3 -3
  13. package/build/cjs/chunk-4PFYL4UI.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 +6 -6
  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
@@ -0,0 +1,314 @@
1
+ ---
2
+ title: Apply actions
3
+ description: Apply and validate ontology actions from React with useOsdkAction, including error handling, debounced validation, and batch application.
4
+ foundryDocs:
5
+ - title: Action types
6
+ path: action-types/overview
7
+ ---
8
+
9
+ {/* cspell:ignore debounced refetches */}
10
+
11
+ Use `useOsdkAction` to apply an action, validate its parameters before submitting, and track pending and error state. When an action succeeds, the cache refetches every object it edited, so components that show those objects update without extra code.
12
+
13
+ ## Apply an action
14
+
15
+ Pass the action from your generated SDK, then call `applyAction` with its parameters:
16
+
17
+ ```tsx title="src/PromoteButton.tsx"
18
+ import { Employee, modifyEmployee } from "@my-app/sdk";
19
+ import { useOsdkAction } from "@osdk/react";
20
+
21
+ export function PromoteButton({
22
+ employee,
23
+ jobTitle,
24
+ }: {
25
+ employee: Employee.OsdkInstance;
26
+ jobTitle: string;
27
+ }) {
28
+ const { applyAction, isPending, error } = useOsdkAction(modifyEmployee);
29
+
30
+ async function handleClick() {
31
+ try {
32
+ await applyAction({ employee, jobTitle });
33
+ } catch (e) {
34
+ console.error("modifyEmployee failed", e);
35
+ }
36
+ }
37
+
38
+ return (
39
+ <div>
40
+ <button disabled={isPending} onClick={() => void handleClick()}>
41
+ {isPending ? "Saving…" : `Make ${jobTitle}`}
42
+ </button>
43
+ {error && <p role="alert">Could not update {employee.fullName}.</p>}
44
+ </div>
45
+ );
46
+ }
47
+ ```
48
+
49
+ <Callout type="warn">
50
+ `applyAction` rethrows every failure after it records it in `error`. Always `await` it inside `try`/`catch`, or attach `.catch`, or the failure becomes an unhandled promise rejection.
51
+ </Callout>
52
+
53
+ Parameters are typed from the action's definition. Object parameters accept an object instance or its primary key.
54
+
55
+ ### Return value
56
+
57
+ | Field | Type | Description |
58
+ | --- | --- | --- |
59
+ | `applyAction` | `(args \| args[]) => Promise<ActionEditResponse \| undefined>` | Applies the action. Pass one parameter object, or an array to apply it in a batch. Each parameter object can include `$optimisticUpdate`. Rejects on failure. |
60
+ | `isPending` | `boolean` | `true` while `applyAction` is running. |
61
+ | `data` | `ActionEditResponse \| undefined` | The edits from the last successful application. |
62
+ | `error` | `{ actionValidation?: ActionValidationError; unknown?: unknown } \| undefined` | The last failure from `applyAction` or `validateAction`. Cleared when either is called again. |
63
+ | `validateAction` | `(args) => Promise<ActionValidationResponse \| undefined>` | Checks parameters on the server without applying the action. Rejects on request failure. |
64
+ | `isValidating` | `boolean` | `true` while `validateAction` is running. |
65
+ | `validationResult` | `ActionValidationResponse \| undefined` | The result of the last completed validation. |
66
+
67
+ The hook takes no options. `$optimisticUpdate` is covered in [Optimistic updates](./optimistic-updates.mdx).
68
+
69
+ ## Read the result
70
+
71
+ `data` is an `ActionEditResponse`: a summary of what the action changed, not a value returned by the action's logic.
72
+
73
+ | Field | Type | Description |
74
+ | --- | --- | --- |
75
+ | `type` | `"edits" \| "largeScaleEdits"` | `"largeScaleEdits"` when the action edited too many objects to list. Only `editedObjectTypes` is set in that case. |
76
+ | `addedObjects` | `Array<{ objectType, primaryKey }>` | Objects the action created. |
77
+ | `modifiedObjects` | `Array<{ objectType, primaryKey }>` | Objects the action changed. |
78
+ | `deletedObjects` | `Array<{ objectType, primaryKey }>` | Objects the action deleted. |
79
+ | `addedLinks` / `deletedLinks` | `Array<LinkReference>` | Links created or removed, with both sides and the link type API names. |
80
+ | `deletedObjectsCount` / `deletedLinksCount` | `number` | Counts of deletions. |
81
+ | `editedObjectTypes` | `Array<string>` | API names of every object type the action touched. |
82
+
83
+ `applyAction` resolves to the same value, which is the simplest way to act on a new object's primary key:
84
+
85
+ ```ts
86
+ const result = await applyAction({ employee, jobTitle: "Staff Engineer" });
87
+ const created = result?.type === "edits" ? result.addedObjects : [];
88
+ ```
89
+
90
+ ## Handle errors
91
+
92
+ `error` separates validation failures from everything else:
93
+
94
+ - `error.actionValidation` is an `ActionValidationError`. The server rejected the parameters, for example because a submission criterion failed or a value is out of range.
95
+ - `error.unknown` holds any other failure: network errors, permission errors, or a `PalantirApiError` from Foundry.
96
+
97
+ Do not show `error.actionValidation.message` to users. It is `"Validation Error: "` followed by the raw validation response as JSON. Read the structured response from `error.actionValidation.validation` instead. This helper turns either a validation error or a `validationResult` into messages:
98
+
99
+ ```ts title="src/validationMessages.ts"
100
+ interface ValidationLike {
101
+ result: "VALID" | "INVALID";
102
+ submissionCriteria: Array<{
103
+ result: "VALID" | "INVALID";
104
+ configuredFailureMessage?: string;
105
+ }>;
106
+ parameters: Record<string, { result: "VALID" | "INVALID" }>;
107
+ }
108
+
109
+ export function validationMessages(validation: ValidationLike | undefined): string[] {
110
+ if (validation == null || validation.result === "VALID") {
111
+ return [];
112
+ }
113
+ const messages = validation.submissionCriteria
114
+ .filter((criterion) => criterion.result === "INVALID")
115
+ .map(
116
+ (criterion) =>
117
+ criterion.configuredFailureMessage ?? "The action's conditions are not met.",
118
+ );
119
+ for (const [name, parameter] of Object.entries(validation.parameters)) {
120
+ if (parameter.result === "INVALID") {
121
+ messages.push(`${name} has an invalid value.`);
122
+ }
123
+ }
124
+ return messages;
125
+ }
126
+ ```
127
+
128
+ Use it with the hook's `error`:
129
+
130
+ ```tsx title="src/ActionError.tsx"
131
+ import type { ActionValidationError } from "@osdk/client";
132
+ import { validationMessages } from "./validationMessages";
133
+
134
+ export function ActionError({
135
+ error,
136
+ }: {
137
+ error: { actionValidation?: ActionValidationError; unknown?: unknown } | undefined;
138
+ }) {
139
+ if (error?.actionValidation) {
140
+ return (
141
+ <ul role="alert">
142
+ {validationMessages(error.actionValidation.validation).map((message) => (
143
+ <li key={message}>{message}</li>
144
+ ))}
145
+ </ul>
146
+ );
147
+ }
148
+ if (error?.unknown != null) {
149
+ return <p role="alert">Something went wrong. Try again.</p>;
150
+ }
151
+ return null;
152
+ }
153
+ ```
154
+
155
+ `submissionCriteria[].configuredFailureMessage` is the message the action's author configured in Foundry, so prefer it when it is present.
156
+
157
+ ## Validate before submitting
158
+
159
+ `validateAction` asks the server whether a set of parameters would pass, without applying the action. An `INVALID` result is not an error: it resolves normally and sets `validationResult`. `validateAction` rejects only when the request itself fails, so it needs a `catch` like `applyAction`.
160
+
161
+ Validating on every keystroke sends a request per keystroke. Wrap the call in `useDebouncedCallback`, exported from `@osdk/react`, so it runs once the user pauses:
162
+
163
+ ```tsx title="src/JobTitleForm.tsx"
164
+ import { Employee, modifyEmployee } from "@my-app/sdk";
165
+ import { useDebouncedCallback, useOsdkAction } from "@osdk/react";
166
+ import { type FormEvent, useState } from "react";
167
+ import { ActionError } from "./ActionError";
168
+ import { validationMessages } from "./validationMessages";
169
+
170
+ export function JobTitleForm({ employee }: { employee: Employee.OsdkInstance }) {
171
+ const [jobTitle, setJobTitle] = useState(employee.jobTitle ?? "");
172
+ const {
173
+ applyAction,
174
+ validateAction,
175
+ validationResult,
176
+ isValidating,
177
+ isPending,
178
+ error,
179
+ } = useOsdkAction(modifyEmployee);
180
+
181
+ const validate = useDebouncedCallback(async (value: string) => {
182
+ try {
183
+ await validateAction({ employee, jobTitle: value });
184
+ } catch (e) {
185
+ console.error("Validation request failed", e);
186
+ }
187
+ }, 400);
188
+
189
+ async function handleSubmit(event: FormEvent) {
190
+ event.preventDefault();
191
+ validate.cancel();
192
+ try {
193
+ await applyAction({ employee, jobTitle });
194
+ } catch (e) {
195
+ console.error("modifyEmployee failed", e);
196
+ }
197
+ }
198
+
199
+ const messages = validationMessages(validationResult);
200
+ const canSubmit =
201
+ jobTitle !== "" &&
202
+ validationResult?.result === "VALID" &&
203
+ !isValidating &&
204
+ !isPending;
205
+
206
+ return (
207
+ <form onSubmit={(event) => void handleSubmit(event)}>
208
+ <input
209
+ value={jobTitle}
210
+ placeholder="Job title"
211
+ onChange={(event) => {
212
+ setJobTitle(event.target.value);
213
+ validate(event.target.value);
214
+ }}
215
+ />
216
+ {isValidating && <span>Checking…</span>}
217
+ {messages.map((message) => (
218
+ <p key={message}>{message}</p>
219
+ ))}
220
+ <button type="submit" disabled={!canSubmit}>
221
+ Save
222
+ </button>
223
+ <ActionError error={error} />
224
+ </form>
225
+ );
226
+ }
227
+ ```
228
+
229
+ How validation and application interact:
230
+
231
+ - A new `validateAction` call supersedes one still in flight. The earlier result is discarded and resolves to `undefined`.
232
+ - `validateAction` does nothing and resolves to `undefined` while `applyAction` is running.
233
+ - `applyAction` discards any validation in flight.
234
+ - `validationResult` keeps the last completed result, so it can describe older input. It is not updated during the debounce delay, and `isValidating` can turn `false` while a newer validation is still running. Treat it as a hint for the UI: `applyAction` validates again on the server and reports a failure in `error.actionValidation`.
235
+
236
+ The debounced function also has `cancel()`, which drops a pending call, and `flush()`, which runs it immediately. A pending call is dropped when the component unmounts.
237
+
238
+ ## Apply an action in a batch
239
+
240
+ Pass an array to apply the same action to several parameter sets in one request:
241
+
242
+ ```tsx title="src/MoveTeam.tsx"
243
+ import { Employee, modifyEmployee } from "@my-app/sdk";
244
+ import { useOsdkAction } from "@osdk/react";
245
+
246
+ export function MoveTeam({
247
+ employees,
248
+ department,
249
+ }: {
250
+ employees: Employee.OsdkInstance[];
251
+ department: string;
252
+ }) {
253
+ const { applyAction, isPending } = useOsdkAction(modifyEmployee);
254
+
255
+ async function moveAll() {
256
+ try {
257
+ await applyAction(
258
+ employees.map((employee) => ({ employee, department })),
259
+ );
260
+ } catch (e) {
261
+ console.error("Batch modifyEmployee failed", e);
262
+ }
263
+ }
264
+
265
+ return (
266
+ <button disabled={isPending} onClick={() => void moveAll()}>
267
+ Move {employees.length} employees to {department}
268
+ </button>
269
+ );
270
+ }
271
+ ```
272
+
273
+ A batch is applied with the batch apply endpoint, so it differs from a single call:
274
+
275
+ - A batch that the server rejects reports the failure in `error.unknown`. `error.actionValidation` is set only for single applications.
276
+ - `validateAction` takes one parameter object, not an array.
277
+ - Each item can carry its own `$optimisticUpdate`. They are combined into one optimistic layer.
278
+
279
+ ## Apply an action with the client
280
+
281
+ You can also apply an action with the `Client` from `useOsdkClient`. This bypasses the cache: components do not update until you invalidate the affected data yourself (see [Invalidate the cache](./cache-invalidation.mdx)). Prefer `useOsdkAction` in components.
282
+
283
+ ```ts title="src/updateJobTitle.ts"
284
+ import { Employee, modifyEmployee } from "@my-app/sdk";
285
+ import type { Client } from "@osdk/client";
286
+
287
+ export async function updateJobTitle(
288
+ client: Client,
289
+ employee: Employee.OsdkInstance,
290
+ jobTitle: string,
291
+ ) {
292
+ const validation = await client(modifyEmployee).applyAction(
293
+ { employee, jobTitle },
294
+ { $validateOnly: true },
295
+ );
296
+ if (validation.result === "INVALID") {
297
+ return undefined;
298
+ }
299
+
300
+ return client(modifyEmployee).applyAction(
301
+ { employee, jobTitle },
302
+ { $returnEdits: true },
303
+ );
304
+ }
305
+ ```
306
+
307
+ | Option | Type | Default | Description |
308
+ | --- | --- | --- | --- |
309
+ | `$returnEdits` | `boolean` | `false` | Resolve to an `ActionEditResponse`. Without it, `applyAction` resolves to `undefined`. |
310
+ | `$validateOnly` | `boolean` | `false` | Validate without applying, and resolve to the `ActionValidationResponse`. Cannot be combined with `$returnEdits`. |
311
+
312
+ A single `applyAction` call on the client throws an `ActionValidationError` when validation fails. For several parameter sets, call `client(modifyEmployee).batchApplyAction([...], { $returnEdits: true })`. It accepts `$returnEdits` but not `$validateOnly`.
313
+
314
+ For a generated form with fields for every parameter, see the [ActionForm component](/components/action-form).
@@ -0,0 +1,256 @@
1
+ ---
2
+ title: Aggregate objects
3
+ description: Count, sum, average, and group objects on the server with useOsdkAggregation, without loading the objects into the browser.
4
+ ---
5
+
6
+ {/* cspell:ignore refetches */}
7
+
8
+ `useOsdkAggregation` asks the server for counts, sums, averages, and other metrics over a set of objects, optionally grouped by property values. Only the results come back, so a total over a million objects costs one small response.
9
+
10
+ ## Count and summarize
11
+
12
+ Pass an object type and an `aggregate` with a `$select`. Each key in `$select` is a metric to compute:
13
+
14
+ ```tsx title="src/PayrollSummary.tsx"
15
+ import { Employee } from "@my-app/sdk";
16
+ import { useOsdkAggregation } from "@osdk/react";
17
+
18
+ export function PayrollSummary() {
19
+ const { data, isLoading, error, refetch } = useOsdkAggregation(Employee, {
20
+ aggregate: {
21
+ $select: {
22
+ $count: "unordered",
23
+ "salary:avg": "unordered",
24
+ "salary:max": "unordered",
25
+ "startDate:min": "unordered",
26
+ },
27
+ },
28
+ });
29
+
30
+ return (
31
+ <dl>
32
+ {error && (
33
+ <p role="alert">
34
+ {error.message} <button onClick={() => void refetch()}>Retry</button>
35
+ </p>
36
+ )}
37
+ {isLoading && !data && <p>Calculating…</p>}
38
+ {data && (
39
+ <>
40
+ <dt>Employees</dt>
41
+ <dd>{data.$count}</dd>
42
+ <dt>Average salary</dt>
43
+ <dd>{data.salary.avg?.toFixed(0) ?? "n/a"}</dd>
44
+ <dt>Highest salary</dt>
45
+ <dd>{data.salary.max ?? "n/a"}</dd>
46
+ <dt>Earliest start date</dt>
47
+ <dd>{data.startDate.min ?? "n/a"}</dd>
48
+ </>
49
+ )}
50
+ </dl>
51
+ );
52
+ }
53
+ ```
54
+
55
+ `$count` is read as `data.$count`. A `"property:metric"` key is read as `data.property.metric`, so `"salary:avg"` becomes `data.salary.avg`. The result is fully typed from the keys you pass.
56
+
57
+ ### Metrics
58
+
59
+ | Key | Property types | Result |
60
+ | --- | --- | --- |
61
+ | `$count` | | `number` |
62
+ | `"property:sum"`, `"property:avg"` | Numeric | `number`, or `undefined` when no object has a value |
63
+ | `"property:min"`, `"property:max"` | Numeric, date, timestamp | Same type as the property, or `undefined` |
64
+ | `"property:exactDistinct"` | All | `number` of distinct values |
65
+ | `"property:approximateDistinct"` | All | Estimated `number` of distinct values. Faster on large object types. |
66
+
67
+ TypeScript rejects a metric that does not fit the property, such as `avg` on a string.
68
+
69
+ ## Filter before aggregating
70
+
71
+ `where` takes the same clause as [`useOsdkObjects`](./objects.mdx#filter-with-where). `intersectWith` adds clauses that every object must also match.
72
+
73
+ ```tsx
74
+ const { data } = useOsdkAggregation(Employee, {
75
+ where: { department: "Engineering" },
76
+ intersectWith: [{ where: { startDate: { $gte: "2024-01-01" } } }],
77
+ aggregate: {
78
+ $select: { $count: "unordered", "salary:sum": "unordered" },
79
+ },
80
+ });
81
+ ```
82
+
83
+ `withProperties` defines [derived properties](./object-sets.mdx#add-derived-properties) that `where` can filter on.
84
+
85
+ ## Group results
86
+
87
+ Add `$groupBy` to get one row per group. `data` is then an array; each row has a `$group` object with the group's values, plus the metrics from `$select`.
88
+
89
+ ```tsx title="src/HeadcountByDepartment.tsx"
90
+ import { Employee } from "@my-app/sdk";
91
+ import { useOsdkAggregation } from "@osdk/react";
92
+
93
+ export function HeadcountByDepartment() {
94
+ const { data, isLoading } = useOsdkAggregation(Employee, {
95
+ where: { department: { $isNull: false } },
96
+ aggregate: {
97
+ $groupBy: { department: "exact" },
98
+ $select: { $count: "desc", "salary:avg": "unordered" },
99
+ },
100
+ });
101
+
102
+ return (
103
+ <table>
104
+ <thead>
105
+ <tr>
106
+ <th>Department</th>
107
+ <th>Headcount</th>
108
+ <th>Average salary</th>
109
+ </tr>
110
+ </thead>
111
+ <tbody>
112
+ {isLoading && !data && (
113
+ <tr>
114
+ <td colSpan={3}>Loading…</td>
115
+ </tr>
116
+ )}
117
+ {data?.map((row) => (
118
+ <tr key={row.$group.department}>
119
+ <td>{row.$group.department}</td>
120
+ <td>{row.$count}</td>
121
+ <td>{row.salary.avg?.toFixed(0)}</td>
122
+ </tr>
123
+ ))}
124
+ </tbody>
125
+ </table>
126
+ );
127
+ }
128
+ ```
129
+
130
+ The value of each `$select` key sets the order of the rows: `"asc"` or `"desc"` sorts by that metric, and `"unordered"` leaves it to the server. Above, departments come back largest first.
131
+
132
+ ### Grouping strategies
133
+
134
+ | Strategy | Property types | Groups by |
135
+ | --- | --- | --- |
136
+ | `"exact"` | String, boolean, numeric except `long`, date, timestamp | Each distinct value. |
137
+ | `{ $exactWithLimit: n }` | String, boolean, numeric except `long`, date, timestamp | Each distinct value, at most `n` groups. |
138
+ | `{ $exact: { $limit?, $includeNullValue: true } }` | String, boolean, numeric except `long`, date, timestamp | Each distinct value, plus a group for missing values. `$group` values are then nullable. |
139
+ | `{ $exact: { $limit?, $defaultValue: "…" } }` | String, boolean, numeric except `long`, date, timestamp | Each distinct value, with missing values grouped under the default. |
140
+ | `{ $fixedWidth: n }` | Numeric | Buckets of width `n`. |
141
+ | `{ $ranges: [[start, end], …] }` | Numeric, date, timestamp | The ranges you list. `$group` holds `{ startValue, endValue }`. |
142
+ | `{ $duration: [n, unit] }` | Date, timestamp | Time buckets, such as `[1, "years"]` or `[1, "month"]`. Dates accept day units and up; timestamps also accept seconds, minutes, and hours. |
143
+
144
+ Group by several properties to get one row per combination:
145
+
146
+ ```tsx
147
+ const { data } = useOsdkAggregation(Employee, {
148
+ aggregate: {
149
+ $groupBy: { department: "exact", salary: { $fixedWidth: 25000 } },
150
+ $select: { $count: "unordered" },
151
+ },
152
+ });
153
+ ```
154
+
155
+ <Callout type="info" title="Typing $ranges and $duration">
156
+ The hook infers `aggregate` as a constant, which makes the tuples in `$ranges` and `$duration` read-only. TypeScript then loses the result type and `row.$group` has no properties. Assert the tuple type to keep it: `{ $ranges: [[0, 50000], [50000, 100000]] as [number, number][] }` or `{ $duration: [1, "years"] as [1, "years"] }`.
157
+ </Callout>
158
+
159
+ ```tsx title="src/SalaryBands.tsx"
160
+ import { Employee } from "@my-app/sdk";
161
+ import { useOsdkAggregation } from "@osdk/react";
162
+
163
+ export function SalaryBands() {
164
+ const { data } = useOsdkAggregation(Employee, {
165
+ aggregate: {
166
+ $groupBy: {
167
+ salary: {
168
+ $ranges: [
169
+ [0, 75000],
170
+ [75000, 150000],
171
+ [150000, 1000000],
172
+ ] as [number, number][],
173
+ },
174
+ },
175
+ $select: { $count: "unordered" },
176
+ },
177
+ });
178
+
179
+ return (
180
+ <ul>
181
+ {data?.map((row) => (
182
+ <li key={row.$group.salary.startValue}>
183
+ {row.$group.salary.startValue} to {row.$group.salary.endValue}: {row.$count}
184
+ </li>
185
+ ))}
186
+ </ul>
187
+ );
188
+ }
189
+ ```
190
+
191
+ ## Aggregate an object set
192
+
193
+ To aggregate a set that a type and a `where` cannot express, such as a pivot or a union, pass it as `objectSet`. The first argument must be the type of that set. `where`, `intersectWith`, and `withProperties` still apply on top of it.
194
+
195
+ ```tsx title="src/SalesOfficesByCity.tsx"
196
+ import { Employee, Office } from "@my-app/sdk";
197
+ import { useOsdkAggregation, useOsdkClient } from "@osdk/react";
198
+ import { useMemo } from "react";
199
+
200
+ export function SalesOfficesByCity() {
201
+ const client = useOsdkClient();
202
+ const salesOffices = useMemo(
203
+ () => client(Employee).where({ department: "Sales" }).pivotTo("office"),
204
+ [client],
205
+ );
206
+
207
+ const { data } = useOsdkAggregation(Office, {
208
+ objectSet: salesOffices,
209
+ aggregate: {
210
+ $groupBy: { city: "exact" },
211
+ $select: { $count: "desc" },
212
+ },
213
+ });
214
+
215
+ return (
216
+ <ul>
217
+ {data?.map((row) => (
218
+ <li key={row.$group.city}>
219
+ {row.$group.city}: {row.$count} offices
220
+ </li>
221
+ ))}
222
+ </ul>
223
+ );
224
+ }
225
+ ```
226
+
227
+ `objectSet` must be an `ObjectSet`, not `undefined`, and works with object types only. The `objectSet` field returned by [`useOsdkObjects`](./objects.mdx) and [`useObjectSet`](./object-sets.mdx) is `undefined` until their first page loads, so build the set with the client as above when you need it on the first render. See [Work with object sets](./object-sets.mdx) for union, intersect, and subtract.
228
+
229
+ ## Refresh and disable
230
+
231
+ Aggregations recompute when an action changes the object type, like other queries. `refetch` invalidates the object type, which refetches every cached query for that type.
232
+
233
+ With `enabled: false`, the hook does not fetch and returns `data: undefined`, `isLoading: false`, and `error: undefined`. `refetch` does nothing while disabled.
234
+
235
+ ## Reference
236
+
237
+ ### `useOsdkAggregation(type, options)`
238
+
239
+ | Option | Type | Default | Description |
240
+ | --- | --- | --- | --- |
241
+ | `aggregate` | `{ $select, $groupBy? }` | Required | The metrics to compute and the optional grouping. |
242
+ | `aggregate.$select` | `{ [metric]: "unordered" \| "asc" \| "desc" }` | Required | Metric keys, such as `$count` or `"salary:avg"`, and how to order groups by them. |
243
+ | `aggregate.$groupBy` | `{ [property]: strategy }` | | Group by these properties. See [Grouping strategies](#grouping-strategies). |
244
+ | `where` | `WhereClause<T>` | | Filter the objects first. |
245
+ | `intersectWith` | `Array<{ where: WhereClause<T> }>` | | Additional filters that every object must also match. |
246
+ | `withProperties` | `DerivedProperty.Clause` | | Derived properties that `where` can reference. |
247
+ | `objectSet` | `ObjectSet<T>` | | Aggregate this set instead of every object of `type`. Object types only. |
248
+ | `enabled` | `boolean` | `true` | When `false`, no request is made. |
249
+ | `dedupeIntervalMs` | `number` | `2000` | Identical aggregations within this window share one request. |
250
+
251
+ | Return | Type | Description |
252
+ | --- | --- | --- |
253
+ | `data` | Result object, array of rows, or `undefined` | An object of metrics without `$groupBy`; an array of rows with `$group` and metrics with it. |
254
+ | `isLoading` | `boolean` | `true` while a request is in flight. |
255
+ | `error` | `Error \| undefined` | The last error, if the aggregation failed. |
256
+ | `refetch` | `() => Promise<void>` | Invalidate the object type and recompute. No-op while disabled. |