Last active
March 27, 2023 10:05
-
-
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'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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