PersistedState
Creates reactive state that is persisted and synchronized across browser sessions and tabs using Web Storage.
0
Check storage in dev toolsUsage
import { PersistedState } from 'svxui';
let persisted = new PersistedState('storageKey', 0);
// Disconnect sync state to storage
persisted.disconnect();
// Connect state sync to storage
persisted.connect();
// Check if state is connected
console.log(persisted.connected);
// Get current state value
persisted.current;
// Set current state value
persisted.current = 42;Type Definition
PersistedState
export declare class PersistedState<T> {
/**
* @param key The unique key used to store the state in the storage.
* @param initialValue The initial value of the state if not already present in the storage.
* @param options Configuration options including storage type, serializer for complex data types, and whether to sync state changes across tabs.
*/
constructor(key: string, initialValue?: T, options?: PersistedStateOptions<T>);
/**
* get current state value
*/
get current(): T;
/**
* Set current state value
*/
set current(newValue: T);
/**
* Is sync state storage enabled or not
*/
get connected(): boolean;
/**
* Disconnect sync state to storage
*/
disconnect: () => void;
/**
* Connect sync state to storage
*/
connect: () => void;
}PersistedStateOptions
export type PersistedStateType = 'local' | 'session';
/**
* Custom serializer API
*/
export type PersistedStateSerializer<T> = {
serialize: (value: T) => string;
deserialize: (value: string) => T | undefined;
};
/**
* Persisted state options
*/
export type PersistedStateOptions<T> = {
/**
* The storage type to use.
* @default "local"
*/
storageType?: PersistedStateType;
/**
* The serializer to use.
* @default { serialize: JSON.stringify, deserialize: JSON.parse }
*/
serializer?: PersistedStateSerializer<T>;
/**
* Whether to sync with the state changes from other tabs.
* @default true
*/
syncTabs?: boolean;
/**
* Whether to connect to storage on initialization, which means that updates to the state will
* be persisted to storage and reads from the state will be read from storage.
*
* When `connected` is `false`, the state is not connected to storage and any changes to the state will
* not be persisted to storage and any changes to storage will not be reflected in the state until
* `.connect()` is called.
*
* @default true
*/
connected?: boolean;
};