use-local-slice
Version:
A react hook to use reducers for local state in a typesafe way, with an API like createSlice from redux-starter-kit and immer integration.
21 lines (20 loc) • 1.15 kB
TypeScript
import { Draft } from "immer";
export declare type PayloadAction<P> = {
type: string;
payload: P;
};
export declare type PayloadActionDispatch<P = void> = void extends P ? () => void : (payload: P) => void;
export declare type RedurcerWithoutPayload<S> = (state: S) => S;
export declare type PayloadActionReducer<S, P = void> = (state: Draft<S>, action: PayloadAction<P>) => void | S | Draft<S>;
export declare type ReducerMap<State> = {
[actionType: string]: PayloadActionReducer<State, any>;
};
export declare type DispatcherMap<Reducers extends ReducerMap<any>> = {
[T in keyof Reducers]: Reducers[T] extends RedurcerWithoutPayload<any> ? PayloadActionDispatch<void> : Reducers[T] extends PayloadActionReducer<any, infer P> ? PayloadActionDispatch<P> : never;
};
export interface UseLocalSliceOptions<State, Reducers extends ReducerMap<State>> {
initialState: State;
reducers: Reducers;
slice?: string;
}
export declare function useLocalSlice<State, Reducers extends ReducerMap<State>>({ initialState, reducers, slice }: UseLocalSliceOptions<State, Reducers>): [State, DispatcherMap<Reducers>];