Skip to main content

    React Hooks

    Latest
    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:

    FunctionScope
    Document readdocument:documents:read
    Document write/updatedocument:documents:write
    Document deletedocument:documents:delete
    State readstate:app-states:read
    State writestate:app-states:write
    State deletestate:app-states:delete
    User state readstate:user-app-states:read
    User state writestate:user-app-states:write
    User state deletestate: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:

    FunctionScope
    Use analyzerdavis: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

    useAccessorPermissionsV2(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Load accessor permissions.

    Parameters

    NameTypeDescription
    params*requiredAccessorPermissionsParamsV2Parameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useAllUsersPermissionsV2

    useAllUsersPermissionsV2(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Load all-users permissions.

    Parameters

    NameTypeDescription
    params*requiredLoadAllUsersPermissionsParamsV2Parameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useAnalyzer

    useAnalyzer(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Execute an analyzer with the given data.

    Parameters

    NameTypeDescription
    params*requiredAnalyzerParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useAppFunction

    useAppFunction(params,options?): { cancel, data, error, isError, isLoading, isSuccess, refetch, status }

    Call specified app function by name.

    Parameters

    NameTypeDescription
    params*requiredAppFunctionParamsApp function params.
    optionsHookOptionsAdditional options for the react hook.

    useAppState

    useAppState(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Gets app state

    Parameters

    NameTypeDescription
    params*requiredAppStateParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useAppStates

    useAppStates(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    List app states

    Parameters

    NameTypeDescription
    params*requiredAppStatesParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useCreateDocument

    useCreateDocument(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Create a new document.

    useCreatePermissionsV2

    useCreatePermissionsV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Create a new permissions.

    useCreateSettings

    ⚠️ Deprecated Use V2 instead.

    useCreateSettings(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Create a new setting.

    useCreateSettingsV2

    useCreateSettingsV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Create a new setting.

    useDeleteAccessorPermissionsV2

    useDeleteAccessorPermissionsV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Delete the accessor permissions

    useDeleteAllUsersPermissionsV2

    useDeleteAllUsersPermissionsV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Delete the all-users permissions

    useDeleteAppState

    useDeleteAppState(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Deletes app state

    useDeleteAppStates

    useDeleteAppStates(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Delete all app states

    useDeleteDocument

    useDeleteDocument(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Delete the document

    useDeleteSettings

    ⚠️ Deprecated Use V2 instead.

    useDeleteSettings(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Delete the setting

    useDeleteSettingsV2

    useDeleteSettingsV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Delete the setting

    useDeleteUserAppState

    useDeleteUserAppState(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Delete user app state

    useDeleteUserAppStates

    useDeleteUserAppStates(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Delete all user app states

    useDocument

    useDocument(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Retrieve metadata and content for documents.

    Parameters

    NameTypeDescription
    params*requiredDocumentParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useDocumentMetaData

    useDocumentMetaData(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Retrieve document metadata.

    Parameters

    NameTypeDescription
    params*requiredDocumentMetaDataParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useDownloadDocument

    useDownloadDocument(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Download document content

    Parameters

    NameTypeDescription
    params*requiredDownloadDocumentParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useDql

    useDql(query,options?): UseDqlResult<T>

    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: true to keep them running.
    • Results are cached for 60 seconds by default (staleTime). Calling refetch while data is still fresh returns the cached result; use forceRefetch to bypass the cache.
    • The hook automatically retries on HTTP 429 (Too Many Requests) responses using the retryAfterSeconds header when available, falling back to exponential back-off.
    • When enablePreview is set on the query params, intermediate partial results are exposed via data while the query is still running.

    Parameters

    NameTypeDescription
    query*requiredstring | 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.

    optionsUseDqlOptions<T>Optional configuration for the hook behavior.

    Returns

    Return typeDescription
    UseDqlResultReturns 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 useDql hook instead.

    useDqlQuery(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Use this hook to execute a DQL query.

    Parameters

    NameTypeDescription
    paramsDEPRECATED*requiredQueryParamsQuery and enrich options that will be executed.
    optionsDEPRECATEDHookOptionsAdditional 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.

    useEffectivePermissions(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Retrieve effective settings permissions for the calling user.

    Parameters

    NameTypeDescription
    paramsDEPRECATED*requiredOmit<{ abortSignal, body } | "abortSignal">Parameters for the client sdk call.
    optionsDEPRECATEDHookOptionsAdditional options for the react hook.

    useEffectivePermissionsV2

    useEffectivePermissionsV2(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Retrieve effective settings permissions for the calling user.

    Parameters

    NameTypeDescription
    params*requiredOmit<{ abortSignal, body } | "abortSignal">Parameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useGrailFields

    useGrailFields(options): UseGrailFieldsResult<TData>

    Fetches Grail fields from both autocomplete and DSS query sources and exposes standard React Query status flags.

    Parameters

    NameType
    options*requiredUseGrailFieldsOptions<TData>

    Returns

    Return typeDescription
    UseGrailFieldsResult

    The raw query data (or the value returned by select), plus React Query state flags (isLoading, isError, isSuccess, errors, refetch, cancel).

    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

    useListDocuments(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    List all documents accessible to you.

    Parameters

    NameTypeDescription
    params*requiredundefined | ListDocumentsParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    usePermissionsV2

    usePermissionsV2(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Load permissions.

    Parameters

    NameTypeDescription
    params*requiredPermissionsParamsV2Parameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useSetAppState

    useSetAppState(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Updates app state

    useSetUserAppState

    useSetUserAppState(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Updates user app state

    useSettings

    ⚠️ Deprecated Use V2 instead.

    useSettings(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Retrieve metadata and content for settings.

    Parameters

    NameTypeDescription
    paramsDEPRECATED*requiredSettingsParamsParameters for the client sdk call.
    optionsDEPRECATEDHookOptionsAdditional options for the react hook.

    useSettingsObjects

    ⚠️ Deprecated Use V2 instead.

    useSettingsObjects(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Retrieve metadata and content for settings.

    Parameters

    NameTypeDescription
    paramsDEPRECATED*requiredSettingsObjectParamsParameters for the client sdk call.
    optionsDEPRECATEDHookOptionsAdditional options for the react hook.

    useSettingsObjectsV2

    useSettingsObjectsV2(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Retrieve metadata and content for settings.

    Parameters

    NameTypeDescription
    params*requiredSettingsObjectParamsV2Parameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useSettingsV2

    useSettingsV2(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Retrieve metadata and content for settings.

    Parameters

    NameTypeDescription
    params*requiredSettingsParamsV2Parameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useTransferOwnershipV2

    useTransferOwnershipV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Transfer ownership.

    useUpdateAccessorPermissionsV2

    useUpdateAccessorPermissionsV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Update accessor permissions.

    useUpdateAllUsersPermissionsV2

    useUpdateAllUsersPermissionsV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Update all-users permissions.

    useUpdateDocument

    useUpdateDocument(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Update metadata and content.

    useUpdateDocumentMetadata

    useUpdateDocumentMetadata(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Update document metadata

    useUpdateSettings

    ⚠️ Deprecated Use V2 instead.

    useUpdateSettings(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Update metadata and content.

    useUpdateSettingsV2

    useUpdateSettingsV2(): { data, error, errorDetails, execute, isError, isLoading, isSuccess, status }

    Update metadata and content.

    useUser

    useUser(uuid,options): UseUserResult

    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

    NameTypeDescription
    uuid*requiredundefined | stringThe user UUID to fetch, or undefined to disable the query.
    options*requiredUseUserOptionsAdditional 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

    useUserAppState(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    Get user app state

    Parameters

    NameTypeDescription
    params*requiredUserAppStateParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useUserAppStates

    useUserAppStates(params,options?): { cancel, data, error, errorDetails, isError, isLoading, isSuccess, refetch, status }

    List user app states

    Parameters

    NameTypeDescription
    params*requiredUserAppStatesParamsParameters for the client sdk call.
    optionsHookOptionsAdditional options for the react hook.

    useUsers

    useUsers(uuids,options): UseUsersResult

    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

    NameTypeDescription
    uuids*requiredArray<string>Array of user UUIDs to fetch.
    options*requiredUseUserOptionsAdditional 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

    NameType
    props*requiredDqlQueryParamsContextProps

    Functions

    UseUsersProvider

    UseUsersProvider(props): ReactElement<any | string | JSXElementConstructor<any>>

    Provider component for configuring the useUser and useUsers hooks.

    Parameters

    NameType
    props*requiredUseUsersConfig

    Code example

    <UseUsersProvider levelType="account" levelId="abc-123">
    <MyTable />
    </UseUsersProvider>

    getGrailFieldsQueryOptions

    getGrailFieldsQueryOptions(autocompleteOptions,dssOptions): GrailFieldsQueryOptions

    Creates combined query options for both autocomplete and DSS queries used in useGrailFields. This allows consumers to prefetch both queries in parallel.

    Parameters

    NameTypeDescription
    autocompleteOptions*requiredAutocompleteQueryOptionsOptions for the autocomplete query.
    dssOptions*requiredDssQueryOptionsOptions 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.

    Types

    AnalyzerHookOptions

    Properties

    NameTypeDescription
    autoFetchDEPRECATED*requiredbooleanIf set to true, the hook will execute the query immediately. If set to false, the query only executes when calling refetch.
    autoFetchOnUpdateDEPRECATED*requiredbooleanIf set to true, the hook will execute the query on a component update. If set to false, it is not executed on update.
    onErrorDEPRECATED(error: Error) => void

    AutocompleteQueryOptions

    Options for the autocomplete query passed to useGrailFields.

    Properties

    NameTypeDescription
    enabledbooleanWhether the query is enabled.
    query*requiredstringThe DQL query string used to derive autocomplete field suggestions.
    retrynumber | booleanNumber of retries or boolean to indicate whether to retry on failure.
    staleTimenumberTime in milliseconds before the query is considered stale.

    DqlQueryParams

    Parameters for query execution.

    Properties

    NameTypeDescription
    defaultSamplingRationumberDefault 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.
    defaultScanLimitGbytesnumberDefault 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.
    defaultTimeframeEndstringThe 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.
    defaultTimeframeStartstringThe 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.
    dtClientContextstringThe 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.
    enablePreviewbooleanRequest preview results. If a preview is available within the requestTimeoutMilliseconds, then it will be returned as part of the response.
    enforceQueryConsumptionLimitboolean(DEPRECATED use body parameter 'enforceQueryConsumptionLimit' instead) If set, query consumption limit will be enforced.
    enrichstringIf set additional data will be available in the metadata section.
    fetchTimeoutSecondsnumberThe 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.
    filterSegmentsFilterSegmentsRepresents a collection of filter segments.
    includeContributionsbooleanIndicates 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.
    includeTypesbooleanParameter to exclude the type information from the query result. In case not specified, the type information will be included.
    localestringThe 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'.
    maxResultBytesnumberThe 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.
    maxResultRecordsnumberThe maximum number of returned query result records. No upper limit.
    query*requiredstringThe full query string.
    queryOptionsQueryOptionsQuery options enhance query functionality for Dynatrace internal services.
    requestTimeoutMillisecondsnumberThe 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.
    timezonestringThe 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

    NameTypeDescription
    defaultSamplingRationumberDefault 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.
    defaultScanLimitGbytesnumberDefault 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.
    defaultTimeframeEndstringThe 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.
    defaultTimeframeStartstringThe 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.
    dtClientContextstringThe 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.
    enablePreviewbooleanRequest preview results. If a preview is available within the requestTimeoutMilliseconds, then it will be returned as part of the response.
    enforceQueryConsumptionLimitboolean(DEPRECATED use body parameter 'enforceQueryConsumptionLimit' instead) If set, query consumption limit will be enforced.
    enrichstringIf set additional data will be available in the metadata section.
    fetchTimeoutSecondsnumberThe 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.
    filterSegmentsFilterSegmentsRepresents a collection of filter segments.
    includeContributionsbooleanIndicates 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.
    includeTypesbooleanParameter to exclude the type information from the query result. In case not specified, the type information will be included.
    localestringThe 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'.
    maxResultBytesnumberThe 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.
    maxResultRecordsnumberThe maximum number of returned query result records. No upper limit.
    queryOptionsQueryOptionsQuery options enhance query functionality for Dynatrace internal services.
    requestTimeoutMillisecondsnumberThe 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.
    timezonestringThe 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

    NameTypeDescription
    dataObject*required"logs" | "spans" | "smartscape.nodes" | "metrics"The target DSS data object ("logs", "spans", "smartscape.nodes", or "metrics").
    enabledbooleanWhether the query is enabled.
    requestTimeoutMillisecondsnumberOptional timeout in milliseconds for the DSS query request.
    retrynumber | booleanNumber of retries or boolean to indicate whether to retry on failure.
    staleTimenumberTime 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

    NameType
    id*requiredstring
    variablesArray<FilterSegmentVariableDefinition>

    FilterSegmentVariableDefinition

    Defines a variable with a name and a list of values.

    Properties

    NameType
    name*requiredstring
    values*requiredArray<string>

    FilterSegments

    Represents a collection of filter segments.

    GrailFieldQueryOption

    A configured query-option object suitable for passing to queryClient.prefetchQuery() or queryClient.fetchQuery().

    Properties

    NameTypeDescription
    enabledbooleanWhether the query is enabled.
    queryFn*required(context: { signal }) => Promise<TData>The function that fetches the data.
    queryKey*requiredThe query key used for caching and invalidation.
    retrynumber | booleanNumber of retries or boolean to indicate whether to retry on failure.
    staleTimenumberTime in milliseconds before the query is considered stale.

    GrailFieldsQueryOptions

    Return type of getGrailFieldsQueryOptions, containing query options for both autocomplete and DSS queries.

    Properties

    NameType
    autocomplete*requiredGrailFieldQueryOption<AutocompleteResponse>
    dss*requiredGrailFieldQueryOption<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

    NameTypeDescription
    enabledbooleanWhether the query is enabled.
    retrynumber | booleanNumber of retries or boolean to indicate whether to retry on failure.
    staleTimenumberTime in milliseconds before the query is considered stale.

    RefetchOptions

    Options for the refetch functions returned by the useDql hook.

    Properties

    NameTypeDescription
    cancelRefetchboolean

    If set to true, a currently running request will be cancelled before a new request is made

    If set to false, no refetch will be made if there is already a request running.

    Defaults to true.

    throwOnErrorboolean

    TypedQueryResult

    Generic type that allows to type data returned from Grail.

    Properties

    NameTypeDescription
    metadata*requiredUseDqlMetadata
    records*requiredArray<T>
    types*requiredArray<RangedFieldTypes>The data types for the result records.

    UseDqlGrailMetadata

    Collects various bits of metadata information.

    Properties

    NameTypeDescription
    analysisTimeframeUseDqlTimeframe
    canonicalQuerystringThe canonical form of the query. It has normalized spaces and canonical constructs.
    contributionsContributions
    dqlVersionstringThe version of DQL that was used to process the query request.
    executionTimeMillisecondsnumberThe time it took to execute the query.
    localestringEffective locale for the query.
    notificationsArray<MetadataNotification>Collected messages during the execution of the query.
    querystringThe submitted query.
    queryIdstringThe id of the query
    sampledbooleanTrue if sampling was used for at least one segment.
    scannedBytesnumberNumber of scanned bytes during the query execution.
    scannedDataPointsnumber
    scannedRecordsnumberNumber of scanned records during the query execution.
    timezonestringEffective timezone for the query.

    UseDqlMetadata

    Collects various bits of metadata information.

    Properties

    NameType
    grailUseDqlGrailMetadata
    metricsArray<MetricMetadata>

    UseDqlOptions

    Options for the useDql hook.

    Properties

    NameTypeDescription
    enabledbooleanSet this to false to disable this query from automatically running. Default: true.
    placeholderDataTypedQueryResult<T>If set, this value will be used as the placeholder data while the query is still in the loading state.
    pollRatenumberThe rate at which Grail query is polled.
    refetchIntervalnumberQuery will continuously refetch at this frequency in milliseconds.
    retryOnMountbooleanIf set to false, the query will not be retried on mount if it contains an error. Defaults to true.
    runInBackgroundbooleanIf set to true, the query will run in the background and not cancel when switching focus. Default: false.
    staleTimenumberThe time in milliseconds after which data is considered stale.

    UseDqlResult

    Represents the possible results of the useDql hook.

    Properties

    NameTypeDescription
    cancel*required() => Promise<void>Function to call to cancel to ongoing query
    dataTypedQueryResult<T>The last successfully resolved data for the query.
    error*requirednull | ErrorThe 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*requiredbooleantrue if the query attempt resulted in an error.
    isFetched*requiredbooleantrue if the query has been fetched.
    isFetching*requiredbooleantrue whenever the query is executing, which includes initial pending as well as background refetches.
    isLoading*requiredbooleantrue whenever the first fetch for a query is in-flight.
    isLoadingError*requiredbooleanWill be true if the query failed while fetching for the first time.
    isPending*requiredbooleantrue if there's no cached data and no query attempt was finished yet.
    isPlaceholderData*requiredbooleanWill be true if the data shown is the placeholder data.
    isRefetchError*requiredbooleantrue if the query failed while refetching.
    isStale*requiredbooleantrue if the data in the cache is invalidated or if the data is older than the given staleTime.
    isSuccess*requiredbooleantrue if the query has received a response with no errors and is ready to display the data.
    progress*requiredundefined | numberThe 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

    NameTypeDescription
    endstringThe end time of the timeframe.
    startstringThe start time of the timeframe.

    UseGrailFieldsOptions

    Options for the useGrailFields hook.

    Properties

    NameTypeDescription
    autocompleteQueryOptions*requiredAutocompleteQueryOptionsOptions for the autocomplete query, including the DQL query string and optional cache/retry overrides.
    dssQueryOptions*requiredDssQueryOptionsOptions 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 ({ autocompleteData, dssData }) once both queries succeed. Use this to transform or filter the raw data before it's returned as data. When omitted, data is the full UseGrailFieldsRaw object.

    UseGrailFieldsRaw

    The raw, unprocessed response data returned by the two underlying queries in useGrailFields.

    Properties

    NameTypeDescription
    autocompleteDataAutocompleteResponseResponse data from the autocomplete query.
    dssDataQueryResultResponse data from the DSS query.

    UseGrailFieldsResult

    Return value of the useGrailFields hook.

    Properties

    NameTypeDescription
    cancel*required() => PromiseCancels both underlying in-flight requests by aborting their signals via React Query.
    data*requiredundefined | TDataThe 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*requirednull | ErrorError from the autocomplete query.
    errors.dss*requirednull | ErrorError from the DSS query.
    isError*requiredbooleantrue when either query is in an error state.
    isLoading*requiredbooleantrue when either query is still fetching for the first time.
    isSuccess*requiredbooleantrue 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

    NameTypeDescription
    data*requiredundefined | null | RestUserPublicThe resolved user data, if available.
    error*requirednull | ErrorThe error object, if an error occurred.
    isError*requiredbooleantrue if the query attempt resulted in an error.
    isFetching*requiredbooleantrue whenever the query is executing, including background refetches.
    isLoading*requiredbooleantrue whenever the first fetch for a query is in-flight.
    isPending*requiredbooleantrue if there's no cached data and no query attempt was finished yet.
    isSuccess*requiredbooleantrue if the query has received a response with no errors.
    refetch*required() => voidFunction to manually refetch the user.

    UseUserErrorResult

    Result of the useUser hook when an error occurred.

    Properties

    NameTypeDescription
    data*requiredundefinedThe resolved user data, if available.
    error*requiredErrorThe error object, if an error occurred.
    isError*requiredtruetrue if the query attempt resulted in an error.
    isFetching*requiredbooleantrue whenever the query is executing, including background refetches.
    isLoading*requiredfalsetrue whenever the first fetch for a query is in-flight.
    isPending*requiredfalsetrue if there's no cached data and no query attempt was finished yet.
    isSuccess*requiredfalsetrue if the query has received a response with no errors.
    refetch*required() => voidFunction to manually refetch the user.

    UseUserLoadingResult

    Result of the useUser hook while loading.

    Properties

    NameTypeDescription
    data*requiredundefinedThe resolved user data, if available.
    error*requirednullThe error object, if an error occurred.
    isError*requiredfalsetrue if the query attempt resulted in an error.
    isFetching*requiredbooleantrue whenever the query is executing, including background refetches.
    isLoading*requiredtruetrue whenever the first fetch for a query is in-flight.
    isPending*requiredtruetrue if there's no cached data and no query attempt was finished yet.
    isSuccess*requiredfalsetrue if the query has received a response with no errors.
    refetch*required() => voidFunction to manually refetch the user.

    UseUserOptions

    Options for the useUser and useUsers hooks.

    Properties

    NameTypeDescription
    enabledbooleanSet this to false to disable this query from automatically running. Default: true.
    levelIdstring

    The organizational level ID to use for the IAM API. By default, auto-detected via getEnvironmentId().

    levelTypestring

    The organizational level type to use for the IAM API. Default: "environment".

    staleTimenumber

    The time in milliseconds after which data is considered stale. Default: 300000 (5 minutes).

    UseUserSuccessResult

    Result of the useUser hook when the user was successfully fetched.

    Properties

    NameTypeDescription
    data*requirednull | RestUserPublicThe resolved user data, if available.
    error*requirednullThe error object, if an error occurred.
    isError*requiredfalsetrue if the query attempt resulted in an error.
    isFetching*requiredbooleantrue whenever the query is executing, including background refetches.
    isLoading*requiredfalsetrue whenever the first fetch for a query is in-flight.
    isPending*requiredfalsetrue if there's no cached data and no query attempt was finished yet.
    isSuccess*requiredtruetrue if the query has received a response with no errors.
    refetch*required() => voidFunction to manually refetch the user.

    UseUsersConfig

    Configuration for the UseUsersProvider context.

    Properties

    NameTypeDescription
    levelIdstringOrganizational level ID. Default: auto-detected via getEnvironmentId().
    levelTypestringOrganizational level type. Default: "environment".
    queryClientQueryClientCustom TanStack Query client for caching and state management.

    UseUsersResult

    Aggregated result of the useUsers hook.

    Properties

    NameTypeDescription
    data*requiredMap<string | RestUserPublic>Map of UUID → user data for all successfully resolved users.
    errors*requiredMap<string | Error>Map of UUID → error for all failed queries.
    isError*requiredbooleantrue if any query resulted in an error.
    isFetching*requiredbooleantrue if any query is currently fetching (including background refetches).
    isLoading*requiredbooleantrue if any query is still loading for the first time.
    isSuccess*requiredbooleantrue if all queries have finished successfully.
    refetch*required() => voidFunction to manually refetch all users.
    users*requiredArray<RestUserPublic>Flat array of all successfully resolved users.
    Still have questions?
    Find answers in the Dynatrace Community