Created
November 3, 2019 21:14
-
-
Save remyoudemans/06dbfa7911740a6d1713ccfeec29a884 to your computer and use it in GitHub Desktop.
This file contains 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
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