4

I would like to execute 2 queries with hooks where the second query uses information retrieved in the first one. For example:

const { data, error, loading } = useQuery(GET_DOGS);
const result2 = useQuery(GET_BREEDS, { variables: { dogId: data[0].id } });

Right now I do it using some state and setting the skip parameter on the second hook, however I figure there must be some easier solution which I might be overlooking?

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
Maxim
  • 3,836
  • 6
  • 42
  • 64

1 Answers1

10

Hooks cannot be conditional, so you can't utilize an if statement or an early return like we would do with a Query component. For better or for worse, using the skip parameter is the simplest solution:

const { data, error, loading } = useQuery(GET_DOGS);
const result2 = useQuery(GET_BREEDS, {
  skip: !data,
  variables: { dogId: data && data.dogs[0].id },
});

Incidentally, it's not all that different than how you would probably handle it if it were 2017 and we were still using HOCs and recompose.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Exactly, that's why i indeed didn't include the conditional case. Something's telling me that the plain old `fetch` was nicer to play with? Do you know of a way to use graphql queries similar to `fetch` when using react-apollo? – Maxim Apr 25 '19 at 07:45
  • I'm trying to follow your example. In my code, I get the error `Cannot read property dogs of undefined`. It seems like that data gets evaluated anyway before the query is skipped. How do you get around that? Does this actually work? – 7ball Nov 28 '19 at 17:00
  • @7ball `data` will be initially undefined, so your code should reflect that. I've updated the answer so it's clearer. – Daniel Rearden Nov 28 '19 at 18:03