Reputation: 131
I am trying to make multiple grahql queries in series. The catch here is that I have to consume the response from one and pass it on to as variables for the next one.
I have tried using delay and load. However, my queries are defined on the component mount so it does need the variables to be set upfront. And hence this approach didn't work for me.
I don't see any clear way of doing this or anywhere mentioned in Apollo docs. Any help would be appreciated!
Upvotes: 0
Views: 1281
Reputation: 7666
I would like to address the following first for people new to GraphQL: If you find yourself in the situation that you have waterfall queries or n + 1 queries in GraphQL it is very likely that you are either not leveraging the GraphQL API correctly or your GraphQL API is not well designed. There might be single use cases where this is your only way of handling the situation and I just assume that OP has already tried to avoid the situation in general.
The following is designed for "react-apollo": ">2.1"
. The same can be achieved with using 2 graphql
HOCs and the skip
query option. The idea is to delay the second query using the skip
option until the data for the first query is available.
Disclaimer: The following code is not tested and only serves the purpose of conveying the general idea or pattern.
function MyComponent() {
return (
<Query query={QUERY1}>
{query1 => (
<Query
query={QUERY2}
variables={{ x: query1.data.x }}
skip={query1.loading}
>
{query2 => (
<div>
{JSON.stringify({
query1Data: query1.data,
query2Data: query2.data
})}
</div>
)}
</Query>
)}
</Query>
);
}
Upvotes: 1
Reputation: 870
You can fire the queries manually and chain them.
const { data } = await client.query({
query: QUERY1,
variables: { search: "Fruits" }
});
const { data2 } = await client.query({
query: QUERY2,
variables: { search: data.apple }
});
Wrap this code inside async
function.
Upvotes: 1