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 queries.
Parameters
Name | Type | Description |
---|---|---|
query*required | string | DqlQueryParams | Query and enrich options that will be executed. |
options | UseDqlOptions | Additional options for the React hook. |
Returns
Return type | Description |
---|---|
UseDqlResult | The result of the query, variables indicating the current state and functions to cancel or refetch the query. |
useDqlQuery
⚠️ Deprecated Use
useDql
hook 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<Object | "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<Object | "abortSignal"> | Parameters for the client sdk call. |
options | HookOptions | Additional options for the react hook. |
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.
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. |
Components
DqlQueryParamsProvider
Provider component for Dql query params context to use with the useDql
hook.
Parameters
Name | Type |
---|---|
props*required | DqlQueryParamsContextProps |
Variables
DqlQueryParamsContext: Context<DqlQueryParamsContextProps>
Context storing Dql query params.
Interfaces
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. | |
Object |
DqlQueryParams
Parameters for query execution.
Properties
Name | Type | Description |
---|---|---|
defaultSamplingRatio | number | In case not specified in the DQL string, the sampling ratio defined here is applied. Note that this is only applicable to log queries. |
defaultScanLimitGbytes | number | Limit in gigabytes for the amount data that will be scanned during read. |
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 | If set, query consumption limit will be enforced. |
enrich | string | If set additional data will be available in the metadata section. |
fetchTimeoutSeconds | number | The query will stop reading data after reaching the fetch-timeout. The query execution will continue, providing a partial result based on the read data. |
filterSegments | FilterSegments | Represents a collection of filter segments. |
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 result bytes that this query will return. |
maxResultRecords | number | The maximum number of result records that this query will return. |
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 | In case not specified in the DQL string, the sampling ratio defined here is applied. Note that this is only applicable to log queries. |
defaultScanLimitGbytes | number | Limit in gigabytes for the amount data that will be scanned during read. |
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 | If set, query consumption limit will be enforced. |
enrich | string | If set additional data will be available in the metadata section. |
fetchTimeoutSeconds | number | The query will stop reading data after reaching the fetch-timeout. The query execution will continue, providing a partial result based on the read data. |
filterSegments | FilterSegments | Represents a collection of filter segments. |
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 result bytes that this query will return. |
maxResultRecords | number | The maximum number of result records that this query will return. |
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' |
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.
QueryOptions
Query options enhance query functionality for Dynatrace internal services.
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 | Metadata | Collects various bits of metadata information. |
records*required | Array<T> | |
types*required | Array<RangedFieldTypes> | The data types for the result records. |
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 |
pollRate | number | The rate at which Grail query is polled |
refetchInterval | number | Query will continuously refetch at this frequency in milliseconds |
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 | Object | 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 | Object | 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. |
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 | Object | Function to manually refetch the query. |
state*required | "FAILED" | "RUNNING" | "NOT_STARTED" | "SUCCEEDED" | "RESULT_GONE" | "CANCELLED" | Possible state of the query. |