How to query with result of prior query in React + Apollo GraphQL?

Viewed 427

In one of my components, I'm immediately querying my backend. Afterwards, I want to query my backend again with the data from my first query, so the variables of my second query are from the first.

I've tried useLazyQuery but either it does not work, or I'm incorrectly placing it. I've tried using skip in the useQuery hook but it doesn't seem to work, because I'm the condition I'm testing against to skip, is also the variable I'm using for the query itself, and I'm checking whether or not it is defined.

I'd rather not use compose as I'm mainly working with hooks in my React Component and I'm not sure of how to structure them and fit them in with my code.

I’m also using both query results separately. My backend is structured like a tree so I’m using both one node and its child.

1 Answers

I wouldn't use useLazyQuery for this if I can avoid it, because it's a different query lifecycle than the more common useQuery. It could work, but let's try with useQuery.

You want the first query, query1, to be executed unconditionnaly. Easy.

You want the second query, query2, to be executed only when query1 has returned a result. Then it's a matter of using skip on query2 based on what query1 returned. In the simplest form:

const { loading: loading1, error: error1, data: data1 } = useQuery('...query1...');
const { loading: loading2, error: error2, data: data2 } = useQuery('...query2...', {
  variables: {
    myVariable: data1 && data1.path.to.data,
  }
  skip: !data1, // This is simpler that checking error1 and loading1.
});

Additionally, you might want to prevent the second query from executing if the first query did not return enough results. Depending on your exact schema and query, it could be something like this:

  skip: !data1 || !data1.searchForIDs || data1.searchForIDs.length === 0
Related