0

I'm writing a web app and I need to query Apollo's local state as well as remote API. Apollo graphql HOC does not allow to send multiple queries but offers some compose function. But it seems that @apollo/react-hoc package does not have it. Scripting local state request into remote one does not work unfortunately (according to DevTools, request is sent, but no data is provided). Redux's compose does not help anyway (well, it's clear for me why so). What is the best way to solve this problem WITHOUT React hooks?

1 Answers1

1

According to the @apollo/react-hoc docs, it seems you are able to run multiple queries by nesting one inside another.

By default graphql hooks injects data as a data prop so for multiple queries it will not work without additional configuration. config.name comes to the rescue so you can specify different names for the injected props instead of data.

export default(
  graphql(
    query1, 
    {name: "data1"}
  )(
    graphql(
      query2, 
      {name: "data2"}
    )(YourComponent)
  )
)

Looks way too verbose. So recompose's (essentially redux) compose will help you:

export default compose(
  graphql(query1, {name: "data1"}),
  graphql(query2, {name: "data2"})
)(YourComponent);

To tell the truth, this approach (with compose) is described in their docs but since it's placed somewhere in the middle where config is described, I believe it's better to put examples here for anyone to find when searching for the topic.

Community
  • 1
  • 1
skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • 1
    Note that the example in the docs actually uses the `compose` function from `recompose`, not `redux`, although the two are basically the [same](https://github.com/acdlite/recompose/blob/master/src/packages/recompose/compose.js) [thing](https://github.com/reduxjs/redux/blob/master/src/compose.ts). – Daniel Rearden Oct 07 '19 at 19:07
  • 1
    yeah, nice catch. also thank you for adding link to docs, missed that. – skyboyer Oct 07 '19 at 19:36
  • @skyboyer these queries will run concurrently or be chained together. Means the second query will wait for the completion of the first query? – Krishan Kant Sharma Sep 20 '21 at 10:56
  • @KrishanKantSharma sequentially. If you want to have them running in parallel, [use hooks](https://www.apollographql.com/docs/react/data/queries) - your component may have any amount of hooks that will pull unrelated data in parallel. – skyboyer Sep 20 '21 at 19:18