Using redux's useDispatch in a custom hook yields an error

Viewed 8681

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

1 Answers

Then number of hook calls in each invocation should be the same (that's why you are not allowed to call hooks inside if statements).

To achieve this useFetchEvents hook should return a function that can be conditionally called, e.g. onClick

change useFetchEvents like so:

export function useFetchEvents() {
  const dispatch = useDispatch()
  const { items, loading } = useSelector(state => state.events)
  return () => {
      if (items.length === 0) {
        // Redux action. requestEvents returns object with type.
        dispatch(requestEvents(true))
      }
  }
}

Then in your component do this:

const FrontPage = () => {
  const fetchEvents = useFetchEvents()

  return(
    <div>
      Front Page
      <button onClick={() => fetchEvents()}>
        Fetch events
      </button>
    </div>
  )
}
Related