@larscom/ngrx-signals-storage
Version:
Save signal state (@ngrx/signals) to localstorage/sessionstorage and restore the state on page load (with SSR support).
78 lines (73 loc) • 2.52 kB
TypeScript
import { SignalStoreFeatureResult, SignalStoreFeature, EmptyFeatureResult } from '@ngrx/signals';
interface Config<T> {
/**
* These keys will not get saved to storage
*/
excludeKeys: Array<keyof T>;
/**
* Serializer for the state, by default it uses `JSON.stringify()`
* @param state the last state known before it gets saved to storage
*/
serialize: (state: T) => string;
/**
* Deserializer for the state, by default it uses `JSON.parse()`
* @param state the last state known from the storage location
*/
deserialize: (state: string) => T;
/**
* Save to storage will only occur when this function returns true
* @param state the last state known before it gets saved to storage
*/
saveIf: (state: T) => boolean;
/**
* Function that gets executed on a storage error (get/set)
* @param error the error that occurred
*/
error: (error: any) => void;
}
/**
* Helper function for SSR (Server Side Rendered) apps to get a storage location.
*
* @example
* export const CounterStore = signalStore(
* withState({
* count: 0
* }),
* withStorage('myKey', getStorage('sessionStorage'))
* )
*
* Check out github for more information.
* @see https://github.com/larscom/ngrx-signals-storage
*/
declare function getStorage(storageType: 'localStorage' | 'sessionStorage'): Storage;
/**
* The `withStorage` function that lets you save the state to localstorage/sessionstorage
* and rehydrate the state upon page load.
*
* @param key the key under which the state should be saved into `Storage`
* @param storage an implementation of the `Storage` interface, like: `sessionStorage` or `localStorage`
*
* @example
* // for apps *without* SSR (Server Side Rendering)
* export const CounterStore = signalStore(
* withState({
* count: 0
* }),
* withStorage('myKey', sessionStorage)
* )
*
* @example
* // for apps *with* SSR (Server Side Rendering)
* export const CounterStore = signalStore(
* withState({
* count: 0
* }),
* withStorage('myKey', getStorage('sessionStorage'))
* )
*
* Check out github for more information.
* @see https://github.com/larscom/ngrx-signals-storage
*/
declare function withStorage<State extends SignalStoreFeatureResult>(key: string, storage: Storage, config?: Partial<Config<State['state']>>): SignalStoreFeature<State, EmptyFeatureResult>;
export { getStorage, withStorage };
export type { Config };