hooks/usePersistedState
import { … } from 'zidane-ui'ui/src/hooks/usePersistedState.ts
Functions#
oneOfFunction#
parse for a closed string union: accepts only the listed members.
function oneOf<T extends string>(members: readonly T[]): (raw: string) => T | undefinedType parameters
| Name | Type | Description |
|---|---|---|
| T | extends string |
Parameters
| Name | Type | Description |
|---|---|---|
| members | readonly T[] | The accepted values. |
Returns
(raw: string) => T | undefinedparseBooleanFunction#
parse for a boolean stored as 'true' / 'false'.
function parseBoolean(raw: string): boolean | undefinedParameters
| Name | Type | Description |
|---|---|---|
| raw | string | The stored string. |
Returns
boolean | undefinedreadPersistedFunction#
The value stored under key, parsed; undefined when absent, unrecognised or when storage throws.
function readPersisted<T>(
key: string,
parse: (raw: string) => T | undefined,
): T | undefinedType parameters
| Name | Description |
|---|---|
| T |
Parameters
| Name | Type | Description |
|---|---|---|
| key | string | The |
| parse | (raw: string) => T | undefined | Validates the stored string; |
Returns
T | undefinedusePersistedStateFunction#
useState kept in localStorage under key: hydrates from a valid stored value, writes on every set.
function usePersistedState<T>(
key: string,
fallback: T,
parse: (raw: string) => T | undefined,
serialize?: (value: T) => string | null,
): [T, Dispatch<SetStateAction<T>>]Type parameters
| Name | Description |
|---|---|
| T |
Parameters
| Name | Type | Description |
|---|---|---|
| key | string | The |
| fallback | T | The value when nothing valid is stored. |
| parse | (raw: string) => T | undefined | Validates the stored string. |
| serialize? | (value: T) => string | null | The stored form of a value; |
Returns
[T, Dispatch<SetStateAction<T>>]writePersistedFunction#
Store value under key; null / undefined removes it. Never throws.
function writePersisted(key: string, value: string | null | undefined): voidParameters
| Name | Type | Description |
|---|---|---|
| key | string | The |
| value | string | null | undefined | The serialized value, or |