keyValueStorage
Reference
A localStorage wrapper with built-in error handling. Use it to persist small amounts of widget state across page reloads (e.g., last selected filter, collapsed/expanded state).
const { protrakUtils } = React.useContext(customWidgetContext);
const { keyValueStorage } = protrakUtils;
const storage = keyValueStorage();
Methods
| Method | Signature | Description |
|---|---|---|
setData | (key: string, value: string) => void | Saves a string value under the given key in localStorage |
getData | (key: string) => string | null | Retrieves the stored string, or null if not found |
removeData | (key: string) => void | Deletes the entry for the key |
Note:
localStoragestores only strings. UseJSON.stringify/JSON.parsefor objects and arrays.
Caveats
- Use a unique, widget-specific key prefix (e.g.
'MyWidget_filterValue') to avoid conflicts with other widgets or platform code. localStorageis per-browser and is shared across all tabs. Do not store sensitive data.- Errors (e.g. storage quota exceeded) are silently caught;
setDataandremoveDatawill not throw.
Usage Example
function PersistentFilterWidget(pageContext) {
const { protrakUtils, protrakComponents } =
React.useContext(customWidgetContext);
const { keyValueStorage } = protrakUtils;
const { Box, Label, TextBox, Button, ButtonEnums } = protrakComponents;
const STORAGE_KEY = 'PersistentFilterWidget_search';
const storage = keyValueStorage();
// Initialise from stored value
const [search, setSearch] = React.useState(
storage.getData(STORAGE_KEY) || ''
);
const handleChange = (e) => {
const val = e.target.value;
setSearch(val);
storage.setData(STORAGE_KEY, val);
};
const handleClear = () => {
setSearch('');
storage.removeData(STORAGE_KEY);
};
return (
<Box style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
<Label>Search</Label>
<TextBox
value={search}
onChange={handleChange}
placeholder="Persists across reloads..."
/>
<Button
text="Clear"
appearance={ButtonEnums.Appearance.Subtle}
onClick={handleClear}
/>
</Box>
);
}
Storing objects
const storage = keyValueStorage();
// Save
const prefs = { sortBy: 'Name', ascending: true };
storage.setData('MyWidget_prefs', JSON.stringify(prefs));
// Read
const raw = storage.getData('MyWidget_prefs');
const prefs = raw ? JSON.parse(raw) : { sortBy: 'Name', ascending: true };