swr-global-state
Version:
Zero-setup & simple global state management for React Components
49 lines • 1.91 kB
TypeScript
import type { Key, SWRConfiguration, SWRResponse, MutatorOptions } from 'swr';
import { type RateLimitConfig } from './utils';
export type StateKey = Key;
export type StateMutatorCallback<T> = (currentData: T) => T | Promise<T>;
export type StateMutator<T> = (data: T | StateMutatorCallback<T>, opts?: boolean | MutatorOptions<T>) => void;
/**
* Object to handle custom cache, it consits `onSet` and `onGet` callback.
* @see https://github.com/gadingnst/swr-global-state#persisted-state
*/
export type StatePersistor<T = any> = {
/**
* `onSet` means the callback that to be called when state has triggers changes.
* Exampe: use this to set the data to `localStorage` every state changes.
* @param {StateKey} key is data key
* @param {T} data is new data that has to changed
*/
onSet: (key: StateKey, data: T) => void | Promise<void>;
/**
* `onGet` means the callback that to be called when initial renders.
* Example: use this to get the data from `localStorage`.
* @param {StateKey} key is data key
* @returns {T|Promise<T>} data to be get on initial render
*/
onGet: (key: StateKey) => T | Promise<T>;
};
export interface StoreParams<T> {
key: StateKey;
initial: T;
persistor?: StatePersistor<T>;
onError?: (error: Error) => void;
retryOnError?: boolean;
rateLimit?: RateLimitConfig<T>;
}
/**
* Using global state with SWR helpers
* @param {StoreParams<T>} data state that to be shared or cached
* @see https://github.com/gadingnst/swr-global-state#custom-hooks for example custom hooks usage
*/
export declare function useStore<T, E = any>(data: StoreParams<T>, swrConfig?: SWRConfiguration): readonly [
T,
StateMutator<T>,
SWRResponse<T, E> & {
isLoading: boolean;
error: E;
isPersisting: boolean;
}
];
export default useStore;
//# sourceMappingURL=useStore.d.ts.map