Skip to content

Instantly share code, notes, and snippets.

@safronman
Last active February 19, 2023 14:45
Show Gist options
  • Select an option

  • Save safronman/0a4cd11a96b84ef83d494883b0af296b to your computer and use it in GitHub Desktop.

Select an option

Save safronman/0a4cd11a96b84ef83d494883b0af296b to your computer and use it in GitHub Desktop.
use action hook
// 🔰 Don't write dispacth in componets. Instead of useAppDispatch use useActionsHook
// 🔗 https://medium.com/@d.maklygin/redux-typescript-reuse-the-type-of-an-action-creators-return-value-91663a48858f
import { useMemo } from 'react'
import { ActionCreatorsMapObject, bindActionCreators } from 'redux'
import { useAppDispatch } from './react-redux-hooks'
type IsValidArg<T> = T extends object ? (keyof T extends never ? false : true) : true
export type ActionCreatorResponse<T extends (...args: any[]) => any> = ReturnType<ReturnType<T>>
export type ReplaceReturnType<T, TNewReturn> = T extends (a: infer A) => infer R
? IsValidArg<A> extends true
? (a: A) => TNewReturn
: () => TNewReturn
: never
export type RemapActionCreators<T extends ActionCreatorsMapObject> = {
[K in keyof T]: ReplaceReturnType<T[K], ActionCreatorResponse<T[K]>>
}
export const useActions = <T extends ActionCreatorsMapObject>(actions: T) => {
const dispatch = useAppDispatch()
return useMemo(
() => bindActionCreators<T, RemapActionCreators<T>>(actions, dispatch),
[actions, dispatch]
)
}
// Slice
export const packsReducer = packsSlice.reducer
export const packsThunks = { getPacks, deletePack, updatePack, createNewPack }
export const packsActions = packsSlice.actions
// Component
// when one thunk / action
const { getPacks } = useActions(packsThunks)
// when more
const { createNewPack, setPaginationValue } = useActions({ ...packsThunks, ...packsActions })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment