@plasius/react-state
Version:
Tiny, testable, typesafe React Scoped Store helper.
61 lines (54 loc) • 2.32 kB
text/typescript
import * as react_jsx_runtime from 'react/jsx-runtime';
import * as react from 'react';
import { ReactNode } from 'react';
type Reducer<S, A> = (state: S, action: A) => S;
type Listener = () => void;
type Unsubscribe = () => void;
declare const __noop: null;
interface IState {
}
interface IAction {
type: string;
}
interface Store<S extends IState, A extends IAction> {
getState(): S;
dispatch(action: A): void;
/**
* Subscribe to all state changes.
*/
subscribe(listener: Listener): () => void;
/**
* Subscribe to changes of a specific key in the state.
*/
subscribeToKey<K extends keyof S>(key: K, listener: (value: S[K]) => void): () => void;
/**
* Subscribe to changes in a selected value from the state.
*/
subscribeWithSelector<T>(selector: (state: S) => T, listener: (selected: T) => void): () => void;
}
declare function createStore<S extends IState, A extends IAction>(reducer: Reducer<S, A>, initialState: S): Store<S, A>;
declare function createScopedStoreContext<S extends IState, A extends IAction>(reducer: (state: S, action: A) => S, initialState: S): {
store: Store<S, A>;
Context: react.Context<Store<S, A> | null>;
Provider: ({ children }: {
children: React.ReactNode;
}) => react_jsx_runtime.JSX.Element;
useStore: () => S;
useDispatch: () => ((action: A) => void);
useSelector: <T>(selector: (state: S) => T, isEqual?: (a: T, b: T) => boolean) => T;
};
interface StoreProviderProps<S extends IState, A extends IAction> {
store: Store<S, A>;
children: ReactNode;
}
declare function StoreProvider<S extends IState, A extends IAction>({ store, children, }: StoreProviderProps<S, A>): react_jsx_runtime.JSX.Element;
declare function useStore<S extends IState>(): S;
declare function useDispatch<A extends IAction>(): Store<IState, A>["dispatch"];
declare class MetadataStore<T extends object, Meta extends object> {
private readonly symbol;
constructor(description: string);
set(target: T, meta: Meta): void;
get(target: T): Meta | undefined;
has(target: T): boolean;
}
export { type IAction, type IState, type Listener, MetadataStore, type Reducer, type Store, StoreProvider, type Unsubscribe, __noop, createScopedStoreContext, createStore, useDispatch, useStore };