Multiple queries in a single component with useQuery hook

This seems to be an obvious question, but I’m having a hella time finding an answer. Is it possible to run more than one query with the useQuery hook a single component? Independent queries, in fact. useQuery seems to only work with the exact names loading, error, and data, and you can’t have more than one, of course, since those are declared constants. I’m having to create spurious components just to hold an extra query, which seems like bad practice - two components in the place of one simply because useQuery is a one-off. But I have a component that truly needs to get two separate chunks of data from two different queries. I’m OK with this being a true React/hooks limitation, but I feel like I’m missing something. Thanks in advance!

1 Like

I’m new to apollo and have also run into this issue. I know you can get around this issue you describe the with duplicate query vars by reassigning the loading, error, and data as unique versions of themselves like this:

const { data: otherData, loading: otherLoading, error: otherError } 

but I’m not sure how scalable this solution is.

1 Like

Did you try something like this?

const { data } = useQuery(gql`
query MyQuery {

Basically the same way we can do it in the Explorer | Sandbox?

I have no idea if it works.

You don’t have to destructure the result from useQuery:

const query1Results = useQuery(QUERY1);
const query2Results = useQuery(QUERY2);

return (
1 Like

@atotalpirate I’ve actually not been able to get that to work, which must be a bug. I have to use the exact variable names data, loading, and error for a query to work with the hook. Clearly that makes no sense, but it is my current experience with Apollo Client 3.6.2 and React 18.2.0.

Thanks! That has the disadvantage of not having a “loading” response if the query is slow, but if the query is cached or is reasonably fast, this is a solution.

Well you can change it to have loading states for both queries. data isnt the only property that can be accessed this way

is a nice writeup covering most of this thread and more

1 Like

Are you sure you were renaming the destructured props correctly? Prop renaming is a feature of ES6, and not of any particular library - so if it wasn’t working as expected, there must’ve been another issue somewhere along the line.

If you’re assigning a single variable to the useQuery response, all of the internal props are now accessible from within that variable - e.g. loading can be accessed like this:

const query = useQuery(MY_QUERY);

if (query.loading)
    return <p>Loading...</p>
    return <div>{}</div>

Thanks! That’s useful. Also very useful was the link to the article posted by HailTheJ. I think I’m in pretty good shape now, although I did have behavior that seemed to vary from what I expected from the React docs.