React Hooks
npm install @dynatrace-sdk/react-hooks
Why should I use this package?
This package simplifies interactions with Grail, documents, and app states in React by encapsulating complex state management. It offers easy-to-use hooks that integrate seamlessly with client packages, enhancing developer productivity and usability in React applications.
Simplified data querying from Grail
Traditionally, querying data in Dynatrace involves using the client-query package and managing complex React state. The useDql hook in this package streamlines this process. The following example showcases how to fetch data with a DQL query:
const { data, error, isLoading } = useDql('fetch logs');
This hook is fully compatible with the parameters used in the queryExecute function of the @dynatrace-sdk/client-query package.
For instance, to limit the number of results returned:
const { data, error, isLoading, refetch } = useDql(
{
query: 'fetch logs',
maxResultRecords: 2000,
}
);
You can delay the execution of the query until a user clicks on a button by passing additional query options to the hook:
const { data, error, isLoading, refetch } = useDql('fetch logs', { enabled: false });
function onClickQuery() {
refetch();
}
You should add appropriate scopes to your app's configuration based on the query type. For more details, refer to the Bucket and table permissions in Grail documentation.
Interacting with documents and app states
Beyond DQL queries, our hooks facilitate interactions with documents and app state. They allow control over immediate or deferred query execution.
const { data, error, isLoading } = useDocument({ id: documentId }, { autoFetch: true });
For creating, updating, or deleting documents or app state, an explicit execute call is necessary:
const { data, execute, error } = useCreateDocument();
function onClickCreateDocument() {
execute(DOCUMENT_DATA);
}
Depending on your interaction type, add these scopes to your app configuration:
| Function | Scope |
|---|---|
| Document read | document:documents:read |
| Document write/update | document:documents:write |
| Document delete | document:documents:delete |
| State read | state:app-states:read |
| State write | state:app-states:write |
| State delete | state:app-states:delete |
| User state read | state:user-app-states:read |
| User state write | state:user-app-states:write |
| User state delete | state:user-app-states:delete |
Simplified Use of Davis® Analyzers
Leveraging Davis® analyzers traditionally involves complex state management and polling logic, alongside the @dynatrace-sdk/client-davis-analyzers package. The useAnalyzer hook in this package makes this process much more straightforward:
const { data, error, isLoading } = useAnalyzer({
analyzerName: 'dt.statistics.GenericForecastAnalyzer',
body: {
timeSeriesData: {
expression: query,
},
},
});
This hook supports all the parameters available in the executeAnalyzer method from the @dynatrace-sdk/client-davis-analyzers package.
To defer the execution of the analyzer until a user action, like a button click, configure the hook with additional options:
const { data, error, isLoading, refetch } = useAnalyzer({
analyzerName: 'dt.statistics.GenericForecastAnalyzer',
body: {
timeSeriesData: {
expression: query,
},
},
{
autoFetch: false,
autoFetchOnUpdate: true,
}
});
function onExecuteAnalyzer() {
refetch();
}
In your app's configuration, include the necessary scope:
| Function | Scope |
|---|---|
| Use analyzer | davis:analyzers:execute |
App functions
The useAppFunction hook is the simplest way to call app functions. As the other hooks in this package, it provides state handling for loading and error states:
const { data, error, isLoading } = useAppFunction({ name: 'functionName', data: 'data' });
Sometimes you want to delay the execution of the app function until a user clicks on a button. This can be achieved by passing additional options to the hook:
const { data, error, isLoading, refetch } = useAppFunction({ name: 'functionName', data: 'data' }, { autoFetch: false, autoFetchOnUpdate: false });
function onClick() {
refetch();
}
Hooks
useAccessorPermissionsV2
Load accessor permissions.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | AccessorPermissionsParamsV2 | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useAllUsersPermissionsV2
Load all-users permissions.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | LoadAllUsersPermissionsParamsV2 | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useAnalyzer
Execute an analyzer with the given data.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | AnalyzerParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useAppFunction
Call specified app function by name.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | AppFunctionParams | App function params. |
| options | HookOptions | Additional options for the react hook. |
useAppState
Gets app state
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | AppStateParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useAppStates
List app states
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | AppStatesParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useCreateDocument
Create a new document.
useCreatePermissionsV2
Create a new permissions.
useCreateSettings
⚠️ Deprecated Use V2 instead.
Create a new setting.
useCreateSettingsV2
Create a new setting.
useDeleteAccessorPermissionsV2
Delete the accessor permissions
useDeleteAllUsersPermissionsV2
Delete the all-users permissions
useDeleteAppState
Deletes app state
useDeleteAppStates
Delete all app states
useDeleteDocument
Delete the document
useDeleteSettings
⚠️ Deprecated Use V2 instead.
Delete the setting
useDeleteSettingsV2
Delete the setting
useDeleteUserAppState
Delete user app state
useDeleteUserAppStates
Delete all user app states
useDocument
Retrieve metadata and content for documents.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | DocumentParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useDocumentMetaData
Retrieve document metadata.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | DocumentMetaDataParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useDownloadDocument
Download document content
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | DownloadDocumentParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useDql
React hook for executing DQL (Dynatrace Query Language) queries against Grail.
Use this hook to run DQL queries in React components and manage query state with less boilerplate. It returns query data, loading and error state, and functions to cancel or rerun the query.
- By default, queries that are in-flight are cancelled when the browser tab
loses focus. Set
runInBackground: trueto keep them running. - Results are cached for 60 seconds by default (
staleTime). Callingrefetchwhile data is still fresh returns the cached result; useforceRefetchto bypass the cache. - The hook automatically retries on HTTP 429 (Too Many Requests) responses
using the
retryAfterSecondsheader when available, falling back to exponential back-off. - When
enablePreviewis set on the query params, intermediate partial results are exposed viadatawhile the query is still running.
Parameters
| Name | Type | Description |
|---|---|---|
| query*required | string | DqlQueryParams | A DQL query string, or a DqlQueryParams object for full control over execution parameters (timezone, timeframe, locale, etc.). Parameters provided here are merged with any values from a parent DqlQueryParamsProvider, with per-call values taking precedence. |
| options | UseDqlOptions<T> | Optional configuration for the hook behavior. |
Returns
| Return type | Description |
|---|---|
| UseDqlResult | Returns the query result, loading and error state, progress information, and functions to cancel or rerun the query. |
Basic usage
function HostList() {
const { data, isLoading, error } = useDql(
'fetch dt.entity.host | fields entity.name, state'
);
if (isLoading) return <span>Loading...</span>;
if (error) return <span>Error: {error.message}</span>;
return (
<ul>
{data?.records.map((host) => (
<li key={host['entity.name']}>{host['entity.name']}</li>
))}
</ul>
);
}
Typed records
interface MyRecord {
state: string;
}
const { data } = useDql<MyRecord>(
'fetch dt.entity.host | fields state'
);
// data?.records is typed as MyRecord[]
Advanced query parameters
const result = useDql({
query: 'fetch logs | sort timestamp desc | limit 100',
defaultTimeframeStart: 'now()-2h',
defaultTimeframeEnd: 'now()',
timezone: 'Europe/Berlin',
locale: 'en_US',
enablePreview: true,
});
Shared query parameters via context
<DqlQueryParamsProvider
defaultTimeframeStart="now()-1h"
defaultTimeframeEnd="now()"
>
<HostList />
<LogViewer />
</DqlQueryParamsProvider>
Cancellation and refetching
const { cancel, refetch, forceRefetch } = useDql('fetch logs');
// Cancel the in-flight query
await cancel();
// Refetch only if data is stale
await refetch();
// Force a fresh fetch regardless of stale time
await forceRefetch();
Tracking progress
const { data, state, progress } = useDql('fetch logs | summarize count()');
if (state === 'RUNNING') {
return <ProgressBar value={progress} />;
}
useDqlQuery
⚠️ Deprecated Use
useDqlhook instead.
Use this hook to execute a DQL query.
Parameters
| Name | Type | Description |
|---|---|---|
| QueryParams | Query and enrich options that will be executed. | |
| HookOptions | Additional options for the react hook. |
Returns
| Description |
|---|
| The state of the query, including the result and functions to refetch or cancel the query. |
useEffectivePermissions
⚠️ Deprecated Use V2 instead.
Retrieve effective settings permissions for the calling user.
Parameters
| Name | Type | Description |
|---|---|---|
| Omit<{ abortSignal, body } | "abortSignal"> | Parameters for the client sdk call. | |
| HookOptions | Additional options for the react hook. |
useEffectivePermissionsV2
Retrieve effective settings permissions for the calling user.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | Omit<{ abortSignal, body } | "abortSignal"> | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useGrailFields
Fetches Grail fields from both autocomplete and DSS query sources and exposes standard React Query status flags.
Parameters
| Name | Type |
|---|---|
| options*required | UseGrailFieldsOptions<TData> |
Returns
| Return type | Description |
|---|---|
| UseGrailFieldsResult | The raw query data (or the value returned by |
Basic usage:
const { data, isLoading } = useGrailFields({
autocompleteQueryOptions: { query: 'fetch logs' },
dssQueryOptions: { dataObject: 'logs' },
});
// data.autocompleteData, data.dssData
With select transform:
const { data } = useGrailFields({
autocompleteQueryOptions: { query: 'fetch logs' },
dssQueryOptions: { dataObject: 'logs' },
select: ({ autocompleteData }) =>
autocompleteData?.suggestions?.map((s) => s.suggestion ?? '') ?? [],
});
useListDocuments
List all documents accessible to you.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | undefined | ListDocumentsParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
usePermissionsV2
Load permissions.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | PermissionsParamsV2 | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useSetAppState
Updates app state
useSetUserAppState
Updates user app state
useSettings
⚠️ Deprecated Use V2 instead.
Retrieve metadata and content for settings.
Parameters
| Name | Type | Description |
|---|---|---|
| SettingsParams | Parameters for the client sdk call. | |
| HookOptions | Additional options for the react hook. |
useSettingsObjects
⚠️ Deprecated Use V2 instead.
Retrieve metadata and content for settings.
Parameters
| Name | Type | Description |
|---|---|---|
| SettingsObjectParams | Parameters for the client sdk call. | |
| HookOptions | Additional options for the react hook. |
useSettingsObjectsV2
Retrieve metadata and content for settings.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | SettingsObjectParamsV2 | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useSettingsV2
Retrieve metadata and content for settings.
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | SettingsParamsV2 | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useTransferOwnershipV2
Transfer ownership.
useUpdateAccessorPermissionsV2
Update accessor permissions.
useUpdateAllUsersPermissionsV2
Update all-users permissions.
useUpdateDocument
Update metadata and content.
useUpdateDocumentMetadata
Update document metadata
useUpdateSettings
⚠️ Deprecated Use V2 instead.
Update metadata and content.
useUpdateSettingsV2
Update metadata and content.
useUser
React hook for fetching a single user by UUID.
Internally batches multiple concurrent useUser calls into a single bulk
POST request to the IAM API, deduplicating UUIDs and chunking into batches
of ≤100 to avoid silent truncation.
Parameters
| Name | Type | Description |
|---|---|---|
| uuid*required | undefined | string | The user UUID to fetch, or undefined to disable the query. |
| options*required | UseUserOptions | Additional options for the hook. |
Returns
| Description |
|---|
| The user data, loading state, and error information. |
Code example
const { data: user, isLoading, error } = useUser('user-uuid-123');
useUserAppState
Get user app state
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | UserAppStateParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useUserAppStates
List user app states
Parameters
| Name | Type | Description |
|---|---|---|
| params*required | UserAppStatesParams | Parameters for the client sdk call. |
| options | HookOptions | Additional options for the react hook. |
useUsers
React hook for fetching multiple users by their UUIDs.
Internally batches all UUID lookups into chunked bulk POST requests to the IAM API (≤100 UUIDs per chunk), with per-UUID caching.
Parameters
| Name | Type | Description |
|---|---|---|
| uuids*required | Array<string> | Array of user UUIDs to fetch. |
| options*required | UseUserOptions | Additional options for the hook. |
Returns
| Description |
|---|
| Aggregated result with a Map of UUID→user data and loading states. |
Code example
const { data, users, isLoading } = useUsers(['uuid-1', 'uuid-2', 'uuid-3']);
Components
DqlQueryParamsProvider
Provider component for Dql query params context to use with the useDql hook.
Parameters
| Name | Type |
|---|---|
| props*required | DqlQueryParamsContextProps |
Functions
UseUsersProvider
Provider component for configuring the useUser and useUsers hooks.
Parameters
| Name | Type |
|---|---|
| props*required | UseUsersConfig |
Code example
<UseUsersProvider levelType="account" levelId="abc-123">
<MyTable />
</UseUsersProvider>
getGrailFieldsQueryOptions
Creates combined query options for both autocomplete and DSS queries used in useGrailFields. This allows consumers to prefetch both queries in parallel.
Parameters
| Name | Type | Description |
|---|---|---|
| autocompleteOptions*required | AutocompleteQueryOptions | Options for the autocomplete query. |
| dssOptions*required | DssQueryOptions | Options for the DSS query. |
Returns
| Description |
|---|
| An object containing query options for both autocomplete and DSS queries. |
Code example
const queryClient = useQueryClient();
const { autocomplete, dss } = getGrailFieldsQueryOptions(
{ query: 'fetch logs' },
{ dataObject: 'logs' },
);
await Promise.all([
queryClient.prefetchQuery(autocomplete),
queryClient.prefetchQuery(dss),
]);
Constants
DqlQueryParamsContext
Context storing Dql query params.
Context<DqlQueryParamsContextProps>
Types
AnalyzerHookOptions
Properties
| Name | Type | Description |
|---|---|---|
| boolean | If set to true, the hook will execute the query immediately. If set to false, the query only executes when calling refetch. | |
| boolean | If set to true, the hook will execute the query on a component update. If set to false, it is not executed on update. | |
| (error: Error) => void |
AutocompleteQueryOptions
Options for the autocomplete query passed to useGrailFields.
Properties
| Name | Type | Description |
|---|---|---|
| enabled | boolean | Whether the query is enabled. |
| query*required | string | The DQL query string used to derive autocomplete field suggestions. |
| retry | number | boolean | Number of retries or boolean to indicate whether to retry on failure. |
| staleTime | number | Time in milliseconds before the query is considered stale. |
DqlQueryParams
Parameters for query execution.
Properties
| Name | Type | Description |
|---|---|---|
| defaultSamplingRatio | number | Default sampling ratio. By default no sampling is applied. No upper limit but will be normalized to a power of 10 less than or equal to 100000. |
| defaultScanLimitGbytes | number | Default scan limit. Can be overridden in DQL. Default value is configured on application level (see documentation of FETCH command). No upper limit. Use -1 for no limit. |
| defaultTimeframeEnd | string | The query timeframe 'end' timestamp in ISO-8601 or RFC3339 format. If the timeframe 'start' parameter is missing, the whole timeframe is ignored. Note that if a timeframe is specified within the query string (query) then it has precedence over this query request parameter. |
| defaultTimeframeStart | string | The query timeframe 'start' timestamp in ISO-8601 or RFC3339 format. If the timeframe 'end' parameter is missing, the whole timeframe is ignored. Note that if a timeframe is specified within the query string (query) then it has precedence over this query request parameter. |
| dtClientContext | string | The dt-client-context header is an optional string parameter used for monitoring purposes. When included in a request, it helps retrieve information about the execution of the query. It shouldn't hold sensitive information. |
| enablePreview | boolean | Request preview results. If a preview is available within the requestTimeoutMilliseconds, then it will be returned as part of the response. |
| enforceQueryConsumptionLimit | boolean | (DEPRECATED use body parameter 'enforceQueryConsumptionLimit' instead) If set, query consumption limit will be enforced. |
| enrich | string | If set additional data will be available in the metadata section. |
| fetchTimeoutSeconds | number | The time limit for fetching data. Soft limit as further data processing can happen. No upper limit in API but application level default and maximum fetch timeout also applies. |
| filterSegments | FilterSegments | Represents a collection of filter segments. |
| includeContributions | boolean | Indicates whether bucket contribution information should be included in the query response metadata. When set to true, the response will contain details about how each bucket contributed to the query result. |
| includeTypes | boolean | Parameter to exclude the type information from the query result. In case not specified, the type information will be included. |
| locale | string | The query locale. If none specified, then a language/country neutral locale is chosen. The input values take the ISO-639 Language code with an optional ISO-3166 country code appended to it with an underscore. For instance, both values are valid 'en' or 'en_US'. |
| maxResultBytes | number | The maximum number of serialized result bytes. Applies to records only and is a soft limit, i.e. the last record that exceeds the limit will be included in the response completely. No upper limit, no default value. |
| maxResultRecords | number | The maximum number of returned query result records. No upper limit. |
| query*required | string | The full query string. |
| queryOptions | QueryOptions | Query options enhance query functionality for Dynatrace internal services. |
| requestTimeoutMilliseconds | number | The maximum time the response will be delayed to wait for a result. (This excludes the sending time and time spent in any services between the query-frontend and the client.) If the query finishes within the specified timeout, the query result is returned. Otherwise, the requestToken is returned, allowing polling for the result. |
| timezone | string | The query timezone. If none is specified, UTC is used as fallback. The list of valid input values matches that of the IANA Time Zone Database (TZDB). It accepts values in their canonical names like 'Europe/Paris', the abbreviated version like CET or the UTC offset format like '+01:00' |
DqlQueryParamsContextProps
Properties
| Name | Type | Description |
|---|---|---|
| defaultSamplingRatio | number | Default sampling ratio. By default no sampling is applied. No upper limit but will be normalized to a power of 10 less than or equal to 100000. |
| defaultScanLimitGbytes | number | Default scan limit. Can be overridden in DQL. Default value is configured on application level (see documentation of FETCH command). No upper limit. Use -1 for no limit. |
| defaultTimeframeEnd | string | The query timeframe 'end' timestamp in ISO-8601 or RFC3339 format. If the timeframe 'start' parameter is missing, the whole timeframe is ignored. Note that if a timeframe is specified within the query string (query) then it has precedence over this query request parameter. |
| defaultTimeframeStart | string | The query timeframe 'start' timestamp in ISO-8601 or RFC3339 format. If the timeframe 'end' parameter is missing, the whole timeframe is ignored. Note that if a timeframe is specified within the query string (query) then it has precedence over this query request parameter. |
| dtClientContext | string | The dt-client-context header is an optional string parameter used for monitoring purposes. When included in a request, it helps retrieve information about the execution of the query. It shouldn't hold sensitive information. |
| enablePreview | boolean | Request preview results. If a preview is available within the requestTimeoutMilliseconds, then it will be returned as part of the response. |
| enforceQueryConsumptionLimit | boolean | (DEPRECATED use body parameter 'enforceQueryConsumptionLimit' instead) If set, query consumption limit will be enforced. |
| enrich | string | If set additional data will be available in the metadata section. |
| fetchTimeoutSeconds | number | The time limit for fetching data. Soft limit as further data processing can happen. No upper limit in API but application level default and maximum fetch timeout also applies. |
| filterSegments | FilterSegments | Represents a collection of filter segments. |
| includeContributions | boolean | Indicates whether bucket contribution information should be included in the query response metadata. When set to true, the response will contain details about how each bucket contributed to the query result. |
| includeTypes | boolean | Parameter to exclude the type information from the query result. In case not specified, the type information will be included. |
| locale | string | The query locale. If none specified, then a language/country neutral locale is chosen. The input values take the ISO-639 Language code with an optional ISO-3166 country code appended to it with an underscore. For instance, both values are valid 'en' or 'en_US'. |
| maxResultBytes | number | The maximum number of serialized result bytes. Applies to records only and is a soft limit, i.e. the last record that exceeds the limit will be included in the response completely. No upper limit, no default value. |
| maxResultRecords | number | The maximum number of returned query result records. No upper limit. |
| queryOptions | QueryOptions | Query options enhance query functionality for Dynatrace internal services. |
| requestTimeoutMilliseconds | number | The maximum time the response will be delayed to wait for a result. (This excludes the sending time and time spent in any services between the query-frontend and the client.) If the query finishes within the specified timeout, the query result is returned. Otherwise, the requestToken is returned, allowing polling for the result. |
| timezone | string | The query timezone. If none is specified, UTC is used as fallback. The list of valid input values matches that of the IANA Time Zone Database (TZDB). It accepts values in their canonical names like 'Europe/Paris', the abbreviated version like CET or the UTC offset format like '+01:00' |
DssQueryOptions
Options for the DSS query passed to useGrailFields.
Properties
| Name | Type | Description |
|---|---|---|
| dataObject*required | "logs" | "spans" | "smartscape.nodes" | "metrics" | The target DSS data object ("logs", "spans", "smartscape.nodes", or "metrics"). |
| enabled | boolean | Whether the query is enabled. |
| requestTimeoutMilliseconds | number | Optional timeout in milliseconds for the DSS query request. |
| retry | number | boolean | Number of retries or boolean to indicate whether to retry on failure. |
| staleTime | number | Time in milliseconds before the query is considered stale. |
FilterSegment
A filter segment is identified by an ID. Each segment includes a list of variable definitions.
Properties
| Name | Type |
|---|---|
| id*required | string |
| variables | Array<FilterSegmentVariableDefinition> |
FilterSegmentVariableDefinition
Defines a variable with a name and a list of values.
Properties
| Name | Type |
|---|---|
| name*required | string |
| values*required | Array<string> |
FilterSegments
Represents a collection of filter segments.
GrailFieldQueryOption
A configured query-option object suitable for passing to
queryClient.prefetchQuery() or queryClient.fetchQuery().
Properties
| Name | Type | Description |
|---|---|---|
| enabled | boolean | Whether the query is enabled. |
| queryFn*required | (context: { signal }) => Promise<TData> | The function that fetches the data. |
| queryKey*required | The query key used for caching and invalidation. | |
| retry | number | boolean | Number of retries or boolean to indicate whether to retry on failure. |
| staleTime | number | Time in milliseconds before the query is considered stale. |
GrailFieldsQueryOptions
Return type of getGrailFieldsQueryOptions, containing query options for both autocomplete and DSS queries.
Properties
| Name | Type |
|---|---|
| autocomplete*required | GrailFieldQueryOption<AutocompleteResponse> |
| dss*required | GrailFieldQueryOption<QueryResult> |
QueryOptions
Query options enhance query functionality for Dynatrace internal services.
QueryOverrides
Subset of UseQueryOptions fields (from @tanstack/react-query) forwarded to each internal
useQueries entry. Mirrors the enabled, staleTime, and retry options.
Properties
| Name | Type | Description |
|---|---|---|
| enabled | boolean | Whether the query is enabled. |
| retry | number | boolean | Number of retries or boolean to indicate whether to retry on failure. |
| staleTime | number | Time in milliseconds before the query is considered stale. |
RefetchOptions
Options for the refetch functions returned by the useDql hook.
Properties
| Name | Type | Description |
|---|---|---|
| cancelRefetch | boolean | If set to If set to Defaults to |
| throwOnError | boolean |
TypedQueryResult
Generic type that allows to type data returned from Grail.
Properties
| Name | Type | Description |
|---|---|---|
| metadata*required | UseDqlMetadata | |
| records*required | Array<T> | |
| types*required | Array<RangedFieldTypes> | The data types for the result records. |
UseDqlGrailMetadata
Collects various bits of metadata information.
Properties
| Name | Type | Description |
|---|---|---|
| analysisTimeframe | UseDqlTimeframe | |
| canonicalQuery | string | The canonical form of the query. It has normalized spaces and canonical constructs. |
| contributions | Contributions | |
| dqlVersion | string | The version of DQL that was used to process the query request. |
| executionTimeMilliseconds | number | The time it took to execute the query. |
| locale | string | Effective locale for the query. |
| notifications | Array<MetadataNotification> | Collected messages during the execution of the query. |
| query | string | The submitted query. |
| queryId | string | The id of the query |
| sampled | boolean | True if sampling was used for at least one segment. |
| scannedBytes | number | Number of scanned bytes during the query execution. |
| scannedDataPoints | number | |
| scannedRecords | number | Number of scanned records during the query execution. |
| timezone | string | Effective timezone for the query. |
UseDqlMetadata
Collects various bits of metadata information.
Properties
| Name | Type |
|---|---|
| grail | UseDqlGrailMetadata |
| metrics | Array<MetricMetadata> |
UseDqlOptions
Options for the useDql hook.
Properties
| Name | Type | Description |
|---|---|---|
| enabled | boolean | Set this to false to disable this query from automatically running. Default: true. |
| placeholderData | TypedQueryResult<T> | If set, this value will be used as the placeholder data while the query is still in the loading state. |
| pollRate | number | The rate at which Grail query is polled. |
| refetchInterval | number | Query will continuously refetch at this frequency in milliseconds. |
| retryOnMount | boolean | If set to false, the query will not be retried on mount if it contains an error. Defaults to true. |
| runInBackground | boolean | If set to true, the query will run in the background and not cancel when switching focus. Default: false. |
| staleTime | number | The time in milliseconds after which data is considered stale. |
UseDqlResult
Represents the possible results of the useDql hook.
Properties
| Name | Type | Description |
|---|---|---|
| cancel*required | () => Promise<void> | Function to call to cancel to ongoing query |
| data | TypedQueryResult<T> | The last successfully resolved data for the query. |
| error*required | null | Error | The error object for the query, if an error was thrown. |
| forceRefetch*required | (options: RefetchOptions) => Promise<UseDqlResult<T>> | Function to manually force refetch the query. Ignores stale time. |
| isError*required | boolean | true if the query attempt resulted in an error. |
| isFetched*required | boolean | true if the query has been fetched. |
| isFetching*required | boolean | true whenever the query is executing, which includes initial pending as well as background refetches. |
| isLoading*required | boolean | true whenever the first fetch for a query is in-flight. |
| isLoadingError*required | boolean | Will be true if the query failed while fetching for the first time. |
| isPending*required | boolean | true if there's no cached data and no query attempt was finished yet. |
| isPlaceholderData*required | boolean | Will be true if the data shown is the placeholder data. |
| isRefetchError*required | boolean | true if the query failed while refetching. |
| isStale*required | boolean | true if the data in the cache is invalidated or if the data is older than the given staleTime. |
| isSuccess*required | boolean | true if the query has received a response with no errors and is ready to display the data. |
| progress*required | undefined | number | The progress of the query from 0 to 100. |
| refetch*required | (options: RefetchOptions) => Promise<UseDqlResult<T>> | Function to manually refetch the query. |
| state*required | "RUNNING" | "NOT_STARTED" | "SUCCEEDED" | "RESULT_GONE" | "CANCELLED" | "FAILED" | Possible state of the query. |
UseDqlTimeframe
Represents a timeframe value when no date transformations are applied
Properties
| Name | Type | Description |
|---|---|---|
| end | string | The end time of the timeframe. |
| start | string | The start time of the timeframe. |
UseGrailFieldsOptions
Options for the useGrailFields hook.
Properties
| Name | Type | Description |
|---|---|---|
| autocompleteQueryOptions*required | AutocompleteQueryOptions | Options for the autocomplete query, including the DQL query string and optional cache/retry overrides. |
| dssQueryOptions*required | DssQueryOptions | Options for the DSS query, including the target data object and optional cache/retry overrides. |
| select | (data: UseGrailFieldsRaw) => TData | Selector applied to the raw data object ( |
UseGrailFieldsRaw
The raw, unprocessed response data returned by the two underlying queries in useGrailFields.
Properties
| Name | Type | Description |
|---|---|---|
| autocompleteData | AutocompleteResponse | Response data from the autocomplete query. |
| dssData | QueryResult | Response data from the DSS query. |
UseGrailFieldsResult
Return value of the useGrailFields hook.
Properties
| Name | Type | Description |
|---|---|---|
| cancel*required | () => Promise | Cancels both underlying in-flight requests by aborting their signals via React Query. |
| data*required | undefined | TData | The raw response data from both queries (or the value returned by select once both succeed), or undefined while loading. |
| errors*required | { autocomplete, dss } | Individual errors from each underlying query (null when that query hasn't errored). |
| errors.autocomplete*required | null | Error | Error from the autocomplete query. |
| errors.dss*required | null | Error | Error from the DSS query. |
| isError*required | boolean | true when either query is in an error state. |
| isLoading*required | boolean | true when either query is still fetching for the first time. |
| isSuccess*required | boolean | true when both queries have successfully fetched. |
| refetch*required | () => Promise<Array<unknown>> | Re-triggers both underlying queries. |
UseUserBaseResult
Base result shape shared by all useUser result states.
Properties
| Name | Type | Description |
|---|---|---|
| data*required | undefined | null | RestUserPublic | The resolved user data, if available. |
| error*required | null | Error | The error object, if an error occurred. |
| isError*required | boolean | true if the query attempt resulted in an error. |
| isFetching*required | boolean | true whenever the query is executing, including background refetches. |
| isLoading*required | boolean | true whenever the first fetch for a query is in-flight. |
| isPending*required | boolean | true if there's no cached data and no query attempt was finished yet. |
| isSuccess*required | boolean | true if the query has received a response with no errors. |
| refetch*required | () => void | Function to manually refetch the user. |
UseUserErrorResult
Result of the useUser hook when an error occurred.
Properties
| Name | Type | Description |
|---|---|---|
| data*required | undefined | The resolved user data, if available. |
| error*required | Error | The error object, if an error occurred. |
| isError*required | true | true if the query attempt resulted in an error. |
| isFetching*required | boolean | true whenever the query is executing, including background refetches. |
| isLoading*required | false | true whenever the first fetch for a query is in-flight. |
| isPending*required | false | true if there's no cached data and no query attempt was finished yet. |
| isSuccess*required | false | true if the query has received a response with no errors. |
| refetch*required | () => void | Function to manually refetch the user. |
UseUserLoadingResult
Result of the useUser hook while loading.
Properties
| Name | Type | Description |
|---|---|---|
| data*required | undefined | The resolved user data, if available. |
| error*required | null | The error object, if an error occurred. |
| isError*required | false | true if the query attempt resulted in an error. |
| isFetching*required | boolean | true whenever the query is executing, including background refetches. |
| isLoading*required | true | true whenever the first fetch for a query is in-flight. |
| isPending*required | true | true if there's no cached data and no query attempt was finished yet. |
| isSuccess*required | false | true if the query has received a response with no errors. |
| refetch*required | () => void | Function to manually refetch the user. |
UseUserOptions
Options for the useUser and useUsers hooks.
Properties
| Name | Type | Description |
|---|---|---|
| enabled | boolean | Set this to false to disable this query from automatically running. Default: true. |
| levelId | string | The organizational level ID to use for the IAM API. By default, auto-detected via |
| levelType | string | The organizational level type to use for the IAM API. Default: |
| staleTime | number | The time in milliseconds after which data is considered stale. Default: |
UseUserSuccessResult
Result of the useUser hook when the user was successfully fetched.
Properties
| Name | Type | Description |
|---|---|---|
| data*required | null | RestUserPublic | The resolved user data, if available. |
| error*required | null | The error object, if an error occurred. |
| isError*required | false | true if the query attempt resulted in an error. |
| isFetching*required | boolean | true whenever the query is executing, including background refetches. |
| isLoading*required | false | true whenever the first fetch for a query is in-flight. |
| isPending*required | false | true if there's no cached data and no query attempt was finished yet. |
| isSuccess*required | true | true if the query has received a response with no errors. |
| refetch*required | () => void | Function to manually refetch the user. |
UseUsersConfig
Configuration for the UseUsersProvider context.
Properties
| Name | Type | Description |
|---|---|---|
| levelId | string | Organizational level ID. Default: auto-detected via getEnvironmentId(). |
| levelType | string | Organizational level type. Default: "environment". |
| queryClient | QueryClient | Custom TanStack Query client for caching and state management. |
UseUsersResult
Aggregated result of the useUsers hook.
Properties
| Name | Type | Description |
|---|---|---|
| data*required | Map<string | RestUserPublic> | Map of UUID → user data for all successfully resolved users. |
| errors*required | Map<string | Error> | Map of UUID → error for all failed queries. |
| isError*required | boolean | true if any query resulted in an error. |
| isFetching*required | boolean | true if any query is currently fetching (including background refetches). |
| isLoading*required | boolean | true if any query is still loading for the first time. |
| isSuccess*required | boolean | true if all queries have finished successfully. |
| refetch*required | () => void | Function to manually refetch all users. |
| users*required | Array<RestUserPublic> | Flat array of all successfully resolved users. |