0

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.

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

0

You simply call the hook conditionally, what is strictly forbidden.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.