-
Notifications
You must be signed in to change notification settings - Fork 110
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is it possible to call multiple queries with useQuery? #120
Comments
What you want to do is compose multiple
|
Thank you for your quick response. I understand and we'll call useQuery as described :) |
@FezVrasta I think I am noticing a similar issue, not sure if this is expected behavior. The top level of my app is wrapped in an I have two components in the tree that each call |
I have a simple solution that worked for me.
I am simply renaming the fields useQuery is giving me in the first call, so that they can live in the same scope, otherwise the second query will overwrite the first. |
Because react does not allow you to have a variable number of hooks, I still think there is a usecase for ONE hook that performs multiple queries. In our situation, we are paginating a table and preloading a variable number of next pages. For example, if user visits page 1, we preload page 2 and 3 after the First ideas of API would be something like this: const { data, loading, error } = useQuery(LIST, { variables: { limit: 10, offset: 0 } })
useManyQueries([
[LIST, { skip: !data, variables: { limit: 10, offset: 1 } }],
[LIST, { skip: !data, variables: { limit: 10, offset: 2 } }],
]) In the above example I've hardcoded it which is achievable with a static number of hooks, however if Example: const currentPage = 0
const limit = 10
const numPreloadedPages = someDynamicValue()
// Let's say numPreloadedPages => 4
const { data, loading, error } = useQuery(LIST, { variables: { limit, offset: currentPage * limit } })
const preloadPages = Array.from(new Array(numPreloadedPages)).map((_, i) => i + currentPage + 1)
// => [1, 2, 3, 4]
useManyQueries(preloadPages.map((page) => [
LIST, { skip: !data, variables: { limit, offset: page * limit } }
])) Should I open a new issue for this? |
Why can't you use the existing "skip" option to conditionally run the queries? |
I don't see how that's related and if you read the code I posted I am using the skip option |
It's not needed, you can use Also, to be fair, your example is not that great, why can't you run a single query to get all your pages? You should just change the |
Sorry maybe I'm not explaining the problem well enough.
You're still talking about a static number of
This only works if you have 100% cache redirect coverage, or I think possibly using So if you have previously queried I'm fairly sure about that but please correct me if that's not the case. P.S. if you want to learn how to use the expression "to be fair" correctly this is a good start https://www.collinsdictionary.com/us/dictionary/english/to-be-fair |
mm had same question i have 2 use queries in the same component fetching with different queries, but i see 2 http requests, is it possible to only make 1 request ? is there any configuration i'm missing ? |
@asotog something like this: let DataQuery = gql`
query BlogData {
me {
id
email
}
posts {
id
title
}
}`
function Page() {
let router = useRouter()
let {data, error, loading} = useQuery(DataQuery)
...
// use data.me
// use data.posts
} ?! |
@asotog you want to use the apollo link batch http https://www.apollographql.com/docs/link/links/batch-http/ |
@ivan-kleshnin @TSMMark sorry i'm new to apollo and graphql in general I have something like this:
each of these hooks using useQuery with different queries each, but i see in the network log, 2 requests going to the graphql separate, so my question was if there is any way apollo handles the 2 request at the same time, or i need to put the 2 gql queries in same useQuery, what approach you would take in my case ? thanks in advance |
Two hooks will result in two HTTP requests because by using two hooks you're basically saying: "I want to apply different policies to two queries". Those policies can be, for example:
My code above (single
the consequent
will reuse the cache for |
will try that thanks so much |
@asotog I still think the batch-http link might help you more than you think. It introduces http request batching automatically globally for queries that run "at the same time" within a certain timeout window. Using it, you could keep your multiple However if you insist not using batch-http apollo link, you should follow @ivan-kleshnin's advice. But I will add to it: you might want to consider breaking your one query (comprised of the two smaller queries) into logical query Fragments (see links below). This is similar to how Relay works — Each component may "export" a query Fragment, then a parent component that actually makes the query is responsible for merging the query fragments into one complete query, and to make the actual query to the server. This may help you achieve separation of data concerns, where your component still has defined colocated data dependencies, but you are merging the queries at a higher level to optimize HTTP traffic. https://graphql.org/learn/queries/#fragments |
Something that worked for me was using another component : User_Data.js import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import QUERY from '../../../Queries';
import Car_Info from './Car_Info';
const GET_USER_QUERY = QUERY.User.GET_USER_QUERY;
const User_Data = (props) => {
const userId = props.match.params.id;
const { loading, error, data } = useQuery(GET_USER_QUERY, {
variables: {
id: userId
}
});
if(loading) return `Loading...`;
if(error) return `Error: ${error.message}`;
return (
<Car_Info type={data.getUser.car_type}/>
);
};
export default User_Data; Car_Info.js import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import QUERY from '../../../Queries';
const GET_CAR_QUERY = QUERY.Car.GET_CAR_QUERY;
const Car_Info = ({type}) => {
const userId = props.match.params.id;
const { loading, error, data } = useQuery(GET_CAR_QUERY, {
variables: {
type
}
});
if(loading) return `Loading...`;
if(error) return `Error: ${error.message}`;
return (
<div> Content, etc </div>
);
};
export default Car_Info; Hope this help |
If it's helpful to anyone, here's a great resource with several approaches How to run multiple queries at once using GraphQL and Apollo Client Here's one approach (from the article above): Took me a lot of searching to find this. |
Another simple solution I found useful is to wait on destructuring the results until you can control the name you give each value.
|
@githubjosh I would disagree with assessment in that article which
This just doesn't make sense because we definitely can declare variables separately for each query that being combined
Question, which one sounds better, getting same data with 1 single query OR multiple query with multiple round trip without getting any benefits?
|
Hello, Trying to do as follow :
doesn't work for me. Most of the time on of the two requests just fails. I don't know how is that possible since that's a solution that many people have proved it valid ? how come that doesn't work for me ? This is the whole code :
At the end I get my variable |
Hello everyone, Is this achievable with usequery or should the change happen on server side to be able to send the list of inputs as an array and get the agregated results? Thanks in advance! I need something like this : const listOfValues = data?.values; listOfValues. forEach(val => { |
For the sanity of future generations, give each useQuery call a "queryKey" config variable or you may end up with overlapping queries.
|
Hi,
In advance thank you great library.
In our product, there is the a page which needs data from 2 or 3 GraphQL queries and we want to call multiple queries with one useQuery().
Is it possible to do the same things as compose() method defined in react-apollo?
https://www.apollographql.com/docs/react/react-apollo-migration#compose-to-render-composition
Or should we call useQuery with each queries?
Thanks.
The text was updated successfully, but these errors were encountered: