Skip to content

Instantly share code, notes, and snippets.

@remyoudemans
Created November 3, 2019 21:14
Show Gist options
  • Save remyoudemans/06dbfa7911740a6d1713ccfeec29a884 to your computer and use it in GitHub Desktop.
Save remyoudemans/06dbfa7911740a6d1713ccfeec29a884 to your computer and use it in GitHub Desktop.
import { useCallback } from 'react'
import { ActionCreator, bindActionCreators } from 'redux'
import { useDispatch } from 'react-redux'
export const useBindActionCreator = <DispatchAction>() => {
const dispatch = useDispatch<(action: DispatchAction) => void>()
return <A, C extends ActionCreator<A>>(actionCreator: C) =>
useCallback(
bindActionCreators(actionCreator, dispatch),
[dispatch]
)
}
/* Example usage:
type MyComponentActions = FetchData | FetchMoreData
const MyComponent: ReactFunctionComponent = () => {
const bindActionCreator = useBindActionCreator<MyComponentActions>()
const fetchData = bindActionCreator(MyActionCreators.fetchData)
const fetchMoreData = bindActionCreator(MyActionCreators.fetchMoreData)
return (
<div>
<button onClick={fetchData}>Fetch some data!</button>
<button onClick={fetchMoreData}>Fetch some <b>more data</b>!</button>
</div>
)
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment