Store app and user states
- How to
- 6 minutes
The state service is your best option if your app needs internal global states or user-specific states. One common usage is caching the result of an app function.
This guide explains how to create, update, and delete app states and user app states. The @dynatrace-sdk/react-hooks package provides hooks so you can do all these operations.
When you run your app on your local development server, the states are confined to the local development's scope. So, you won't be in danger of overriding the deployed app's states during development.
States are persistent across updates of an app. So, you must migrate any states needed for a new app version in the app's code.
Set a state by key
To set the app or user app state, you can use the setAppState or setUserAppState hooks from the @dynatrace-sdk/react-hooks package. These hooks provide an execute function to create a new state, and additional fields about the loading status, errors, and response. These fields are common to all the app and user app state hooks. The example below shows how to create an app state for storing weather information:
Add a version field to your state to make future migrations easier.
import React from 'react';
import { useSetAppState } from '@dynatrace-sdk/react-hooks';
import { Button } from '@dynatrace/strato-components/buttons';
import { Page } from '@dynatrace/strato-components-preview/layouts';
export const App = () => {
const { execute } = useSetAppState();
const handleClick = () => {
execute({
key: 'weather',
body: {
value: JSON.stringify({
version: '1',
timestamp: Date.now(),
weather: { city: 'Vienna', temperature: 23, unit: 'celsius' },
}),
validUntilTime: 'now+1d',
},
});
};
return (
<Page>
<Button onClick={handleClick}>Set app state</Button>
</Page>
);
};
This operation requires the following scopes:
state:app-states:writestate:user-app-states:write
State validity
By default, app states and user app states don't expire. To define states that are only valid for a certain period, you can provide an optional validUntilTime, which ensures the presence of the state until the time expires. States are deleted after their validUntilTime elapses.
You can provide the validUntilTime in two ways:
- A relative time format such as
now+1mornow+30d:- The format is
now+NUwhereNis the amount of time,Uis the unit of time (s - seconds, m - minutes, h - hours, d - days).
- The format is
- A timestamp in ISO 8601 format.
For both types, you can specify a timeframe of 1 minute to 90 days.
Every app state hook has an equivalent user app state hook. For instance, the equivalent of useSetAppState is useSetUserAppState. All the examples in this guide use the app state hooks.