[SOLVED] getting error when I run useQuery inside the useEffect hook in react-query – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Karim

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.



Solution

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


This Question was asked in StackOverflow by Karim and Answered by ivanatias It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?