state-jet
Version:
Ultra-lightweight global state management for React
61 lines (54 loc) • 2.38 kB
TypeScript
type Middleware<T> = (key: string, prev: T | undefined, next: T | Action<T>, set?: (value: T) => void) => T | void | Promise<void>;
type Options<T> = {
middleware?: Middleware<T | undefined>[];
persist?: boolean;
encrypt?: boolean;
frameSync?: boolean;
};
type Action<T> = {
type: string;
payload?: T;
};
/**
* Creates a global reactive state with middleware, persistence, and batch updates.
*/
declare const useStateGlobal: <T>(key: string, initialValue?: T, options?: Options<T>) => {
useState: () => T | undefined;
set: (newValue: T | Action<T | undefined> | ((prev: T | undefined) => T | undefined) | undefined, immediate?: boolean) => Promise<void>;
get: () => T | undefined;
undo: () => void;
redo: () => void;
clear: () => void;
};
/**
* Creates a slice that can hold multiple state values.
*/
declare const useSlice: (sliceName: string) => <T>(key: string, initialValue: T, options?: Options<T | undefined>) => {
useState: () => T;
set: (newValue: T | ((prev: T) => T) | Action<T>, immediate?: boolean) => Promise<void>;
get: () => T;
undo: () => void;
redo: () => void;
clear: () => void;
};
/**
* Creates a store with multiple slices.
*/
declare const useStore: <T extends Record<string, ReturnType<typeof useSlice>>>(initializer: () => T) => T;
declare const saveState: <T>(key: string, value: T) => void;
declare const restoreState: <T>(key: string, defaultValue?: T) => any;
declare const optimisticUpdate: <T>(setState: {
set: (value: T) => void;
useState: () => T;
}, updateFn: (prevState: T) => T, apiCall: () => Promise<T>, rollbackFn?: (prevState: T) => T) => Promise<void>;
declare const saveEncryptedState: <T>(key: string, value: T) => void;
declare const restoreEncryptedState: <T>(key: string, defaultValue?: T) => unknown;
declare const mergeCRDT: <T>(localState: T, remoteState: T) => T;
declare const syncCRDT: <T>(remoteState: T, setState: {
useState: () => T;
set: (state: T) => void;
}) => void;
declare const derivedState: <T, D extends {
useState: () => unknown;
}[]>(dependencies: D, computeFn: (...values: { [K in keyof D]: ReturnType<D[K]["useState"]>; }) => T) => () => T;
export { derivedState, mergeCRDT, optimisticUpdate, restoreEncryptedState, restoreState, saveEncryptedState, saveState, syncCRDT, useSlice, useStateGlobal, useStore };