react-tienda
Version:
React Tienda is a lightweight and intuitive global state management library for React, designed to easily share state across components with minimal setup.
39 lines (38 loc) • 2.09 kB
TypeScript
declare type SharedConfigs = Partial<{
shallowCompareOnSetState: boolean;
}>;
declare type GlobalStoreConfig = Partial<{}> & SharedConfigs;
declare type HookOptions = {
resetStoreState: (all?: boolean) => void;
};
declare type HookResultOptions<T> = {
comparer: (oldState: T, newState: T) => boolean;
};
declare type SetState<T> = (s: Partial<T> | ((oldState: T) => Partial<T>), options?: HookResultOptions<T>) => void;
declare type Actions<Y extends string | number | symbol, T> = Record<Y, (state: T, setStoreState: SetState<T>) => (...args: any) => void>;
declare type HookSecond<T, Y extends string | number | symbol> = {
setStoreState: SetState<T>;
actions: Record<Y, (...args: any) => void>;
} & HookOptions;
declare type HookResult<T, Y extends string | number | symbol> = [T, HookSecond<T, Y>];
/**
* @description Will create a global store where state is shared among components that use the returned hook that can be used to set and get the state.
* @advanced You can enter the global (store scope) state using useStore.getGlobalState() or set the global state useStore.setGlobalState
* @author https://github.com/AhmadHddad
* @example export const useStore = createGlobalStore({a:1, b:2});
* @returns hook that is used to connect the component with the store.
* its its really recommended to specify the used store keys in the returned hook (as list of strings) to reduce the component rerendering.
* @example const Component = () => {
* const [storeState, setStoreState] = useStore(["a"]);
*
* return <button onClick={()=> setStoreState({a:3})}>Click me</button>
* }
*/
export default function createGlobalStore<T extends Record<string, unknown>, A extends Actions<string, T>>(initState?: T, actions?: A, storeConfigs?: GlobalStoreConfig): {
(select?: (keyof T)[] | undefined, hookConfigs?: GlobalStoreConfig | undefined): HookResult<T, keyof A>;
setGlobalState(newState: Partial<T>, options?: Partial<{
override: boolean;
}> | undefined): void;
getGlobalState(): T;
};
export {};