Gagan
Gagan

Reputation: 5656

React Query useQuery hooks raising an error → react-hooks/rules-of-hooks

I have a sample component as follows. I am trying to use React Query to get data from my endpoint(Graphql). I have a custom hook which I have also listed below.

const App =(props)=>{  
if (me && me.token) {
    let headers = {
        Authorization: me.token,
    }
    const { loading, error, data } = useGQLQuery('getUploads', GetUploadedFiles, headers)
    let tableData = []
    if (data && data.uploads) {
      tableData = data.uploads
    }
  } else {
    message.info("You need to be logged in to manage your assets!")
    return;
  }
}

Custom Hook →

export const useGQLQuery = (key, query, variables,headers={}, config = {}) => {
  let gqlClient = new GraphQLClient(endpoint)
  const fetchData = async () => gqlClient.request(query, variables, headers)
  return useQuery(key, fetchData, config)
}

I would like to pass the current user's token information in the header.

So far so good.

Now , whenever I am trying to load this compoent, I get the following error

React Hook "useGQLQuery" is called conditionally. 
React Hooks must be called in the exact same order in every component render. 
Did you accidentally call a React Hook after an early return?  react-hooks/rules-of-hooks

I need to pass the current user's token which is why I do this

if (me && me.token) {
    let headers = {
        Authorization: me.token,
    }
    const { loading, error, data } = useGQLQuery('getUploads', GetUploadedFiles, headers)

but it is the point where all issue happens.

Can you please let me know how can I do , what I am trying to do here. Any help with some examples will be a lot of help.

Thanks

Upvotes: 0

Views: 2864

Answers (1)

Ansh Saini
Ansh Saini

Reputation: 415

You're calling a hook inside an if condition. React cannot allow that. It needs a consistent hook call on every re-render to keep track of changes. You need to modify your useGQLQuery hook so that it internally handles your logical conditions like me && me.token.

Here's the explanation to why you can't call hooks from if conditions:

https://reactjs.org/docs/hooks-rules.html#explanation

Upvotes: 1

Related Questions