Skip to main content

    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:

    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?): Object

    Load accessor permissions.

    Parameters

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

    useAllUsersPermissionsV2

    useAllUsersPermissionsV2(params,options?): Object

    Load all-users permissions.

    Parameters

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

    useAnalyzer

    useAnalyzer(params,options?): Object

    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?): Object

    Call specified app function by name.

    Parameters

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

    useAppState

    useAppState(params,options?): Object

    Gets app state

    Parameters

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

    useAppStates

    useAppStates(params,options?): Object

    List app states

    Parameters

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

    useCreateDocument

    useCreateDocument(): Object

    Create a new document.

    useCreatePermissionsV2

    useCreatePermissionsV2(): Object

    Create a new permissions.

    useCreateSettings

    ⚠️ Deprecated Use V2 instead.

    useCreateSettings(): Object

    Create a new setting.

    useCreateSettingsV2

    useCreateSettingsV2(): Object

    Create a new setting.

    useDeleteAccessorPermissionsV2

    useDeleteAccessorPermissionsV2(): Object

    Delete the accessor permissions

    useDeleteAllUsersPermissionsV2

    useDeleteAllUsersPermissionsV2(): Object

    Delete the all-users permissions

    useDeleteAppState

    useDeleteAppState(): Object

    Deletes app state

    useDeleteAppStates

    useDeleteAppStates(): Object

    Delete all app states

    useDeleteDocument

    useDeleteDocument(): Object

    Delete the document

    useDeleteSettings

    ⚠️ Deprecated Use V2 instead.

    useDeleteSettings(): Object

    Delete the setting

    useDeleteSettingsV2

    useDeleteSettingsV2(): Object

    Delete the setting

    useDeleteUserAppState

    useDeleteUserAppState(): Object

    Delete user app state

    useDeleteUserAppStates

    useDeleteUserAppStates(): Object

    Delete all user app states

    useDocument

    useDocument(params,options?): Object

    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?): Object

    Retrieve document metadata.

    Parameters

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

    useDownloadDocument

    useDownloadDocument(params,options?): Object

    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 queries.

    Parameters

    NameTypeDescription
    query*requiredstring | DqlQueryParamsQuery and enrich options that will be executed.
    optionsUseDqlOptionsAdditional options for the React hook.

    Returns

    Return typeDescription
    UseDqlResultThe result of the query, variables indicating the current state and functions to cancel or refetch the query.

    useDqlQuery

    ⚠️ Deprecated Use useDql hook instead.

    useDqlQuery(params,options?): Object

    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?): Object

    Retrieve effective settings permissions for the calling user.

    Parameters

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

    useEffectivePermissionsV2

    useEffectivePermissionsV2(params,options?): Object

    Retrieve effective settings permissions for the calling user.

    Parameters

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

    useListDocuments

    useListDocuments(params,options?): Object

    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?): Object

    Load permissions.

    Parameters

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

    useSetAppState

    useSetAppState(): Object

    Updates app state

    useSetUserAppState

    useSetUserAppState(): Object

    Updates user app state

    useSettings

    ⚠️ Deprecated Use V2 instead.

    useSettings(params,options?): Object

    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?): Object

    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?): Object

    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?): Object

    Retrieve metadata and content for settings.

    Parameters

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

    useTransferOwnershipV2

    useTransferOwnershipV2(): Object

    Transfer ownership.

    useUpdateAccessorPermissionsV2

    useUpdateAccessorPermissionsV2(): Object

    Update accessor permissions.

    useUpdateAllUsersPermissionsV2

    useUpdateAllUsersPermissionsV2(): Object

    Update all-users permissions.

    useUpdateDocument

    useUpdateDocument(): Object

    Update metadata and content.

    useUpdateDocumentMetadata

    useUpdateDocumentMetadata(): Object

    Update document metadata

    useUpdateSettings

    ⚠️ Deprecated Use V2 instead.

    useUpdateSettings(): Object

    Update metadata and content.

    useUpdateSettingsV2

    useUpdateSettingsV2(): Object

    Update metadata and content.

    useUserAppState

    useUserAppState(params,options?): Object

    Get user app state

    Parameters

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

    useUserAppStates

    useUserAppStates(params,options?): Object

    List user app states

    Parameters

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

    Components

    DqlQueryParamsProvider

    Provider component for Dql query params context to use with the useDql hook.

    Parameters

    NameType
    props*requiredDqlQueryParamsContextProps

    Variables

    DqlQueryParamsContext: Context<DqlQueryParamsContextProps>

    Context storing Dql query params.

    Interfaces

    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.
    onErrorDEPRECATEDObject

    DqlQueryParams

    Parameters for query execution.

    Properties

    NameTypeDescription
    defaultSamplingRationumberIn case not specified in the DQL string, the sampling ratio defined here is applied. Note that this is only applicable to log queries.
    defaultScanLimitGbytesnumberLimit in gigabytes for the amount data that will be scanned during read.
    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.
    enforceQueryConsumptionLimitbooleanIf set, query consumption limit will be enforced.
    enrichstringIf set additional data will be available in the metadata section.
    fetchTimeoutSecondsnumberThe query will stop reading data after reaching the fetch-timeout. The query execution will continue, providing a partial result based on the read data.
    filterSegmentsFilterSegmentsRepresents a collection of filter segments.
    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 result bytes that this query will return.
    maxResultRecordsnumberThe maximum number of result records that this query will return.
    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
    defaultSamplingRationumberIn case not specified in the DQL string, the sampling ratio defined here is applied. Note that this is only applicable to log queries.
    defaultScanLimitGbytesnumberLimit in gigabytes for the amount data that will be scanned during read.
    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.
    enforceQueryConsumptionLimitbooleanIf set, query consumption limit will be enforced.
    enrichstringIf set additional data will be available in the metadata section.
    fetchTimeoutSecondsnumberThe query will stop reading data after reaching the fetch-timeout. The query execution will continue, providing a partial result based on the read data.
    filterSegmentsFilterSegmentsRepresents a collection of filter segments.
    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 result bytes that this query will return.
    maxResultRecordsnumberThe maximum number of result records that this query will return.
    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'

    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.

    QueryOptions

    Query options enhance query functionality for Dynatrace internal services.

    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*requiredMetadataCollects various bits of metadata information.
    records*requiredArray<T>
    types*requiredArray<RangedFieldTypes>The data types for the result records.

    UseDqlOptions

    Options for the useDql hook.

    Properties

    NameTypeDescription
    enabledbooleanSet this to false to disable this query from automatically running. Default: true
    pollRatenumberThe rate at which Grail query is polled
    refetchIntervalnumberQuery will continuously refetch at this frequency in milliseconds
    staleTimenumberThe time in milliseconds after which data is considered stale.

    UseDqlResult

    Represents the possible results of the useDql hook.

    Properties

    NameTypeDescription
    cancel*requiredObjectFunction 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*requiredObjectFunction 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.
    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*requiredObjectFunction to manually refetch the query.
    state*required"FAILED" | "RUNNING" | "NOT_STARTED" | "SUCCEEDED" | "RESULT_GONE" | "CANCELLED"Possible state of the query.
    Still have questions?
    Find answers in the Dynatrace Community