getting error when I run useQuery inside the useEffect hook in react-query

Viewed 41

When I run the below code I am getting: Uncaught 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
  useEffect(() => {
    if (user.email) {
      const { data } = GetUserInfo(user.email);
    }
  }, [user.email]);

What I am trying to do is until I get the user email I will not run the getUserInfo query.

3 Answers

As mentioned in the other answer, you can only call hooks at the top level in the body of a functional component/custom hook.

I think you can achieve what you want using the enabled option in useQuery to enable/disable it based on a condition.

Docs example:

function Todos() {
  const [filter, setFilter] = React.useState('')

  const { data } = useQuery(
    ['todos', filter],
    () => fetchTodos(filter),
    {
      // ⬇️ disabled as long as the filter is empty
      enabled: !!filter
    }
  )
     ...
}

Reference:

https://tanstack.com/query/v4/docs/guides/disabling-queries

You can't call a hook inside another hook.

  useEffect(() => {
    if (user.email) {
      const { data } = GetUserInfo(user.email);
    }
  }, [user.email]);

You have to call the hook outside useEffect hook

There are three common reasons you might be seeing it

  1. You might have mismatching versions of React and 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.

In your case you are breaking the rule of hooks that Call Hooks from React function components. GetUserInfo is also hook you are calling in a hook you need to call it outside of useEffect()

for reference documentation

Related