Skip to content

Instantly share code, notes, and snippets.

@T1T4N
Last active March 27, 2023 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save T1T4N/a1c8f78d04bf992f0848a764abe72abd to your computer and use it in GitHub Desktop.
Save T1T4N/a1c8f78d04bf992f0848a764abe72abd to your computer and use it in GitHub Desktop.
Use Redux Toolkit's createSlice with useReducer + export a type union of all its actions defined in 'reducers'
// https://stackoverflow.com/a/64582352
export type SliceActions<T> = {
[K in keyof T]: T[K] extends (...args: any[]) => infer A ? A : never;
}[keyof T];
// USAGE - NOTE: This doesn't work with `extraReducers` and the builder syntax
export type MySlice = typeof slice;
export type StateAction = SliceActions<MySlice['actions']>;
export type SliceReducer = Reducer<IState, StateAction>;
export const useSliceReducer = (initialStateFactory: () => IState) => {
const [state, dispatch] = useReducer<SliceReducer>(
slice.reducer,
initialStateFactory(),
);
return { state, dispatch };
};
export type SliceDispatch = ReturnType<typeof useSliceReducer>['dispatch'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment