I'm trying to implement useDispatch in a custom hook that dispatches a redux action, but I'm getting the following error:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
CODE:
modules file
import { useDispatch, useSelector } from 'react-redux'
export function useFetchEvents() {
const dispatch = useDispatch()
const { items, loading } = useSelector(state => state.events)
if (items.length === 0) {
dispatch(requestEvents(true))
}
}
functional component
import { useFetchEvents } from '../../../modules/events'
const FrontPage = () => {
return(
<div>
Front Page
<button onClick={useFetchEvents}>
Fetch events
</button>
</div>
)
}
export default FrontPage
I've seen the error and read the rules regarding hooks, but if I understand it correctly I should be able to use useDispatch in a custom hook. Like in the following working examples:
https://github.com/mikeour/drinks_drinks_drinks/blob/master/src/hooks/index.js