0

I have two queries:

const GET_FILTERS = gql`
  query getFilters {
    filters @client {
      id
      title
      selected
    }
  }
`

And

const GET_POSTS = gql`
  query getPosts {
    posts {
      id
      author
      status
    }
  }
`

First one fetches the data from a local state using apollo-link-state and the second one is a external call.

I have a HOC for fetching posts setup like this:

const withPosts = (Component) => (props) => (
  <Query
    query={GET_POSTS}  
  >
    {({loading, data, error})} => {
      if(loading) return null
      if(error) return null
      return <Component {...data} {...props}/>
    }}
  </Query>
)

The fetching of the posts is fine but what I would like to do is to add whatever is returned from GET_FILTERS query with every call to GET_POSTS query?

One thing I could do is to wrap withPost in to another, lets say withFilters HOC, and pass the result in to GET_POSTS query as variables but I have been wondering if there is any other way to access that data via some sort of context and for example cache.readQuery using only withPost HOC.

Kocur4d
  • 6,701
  • 8
  • 35
  • 53

1 Answers1

1

Apollo has 'native' tools for HOC pattern, you can compose many (named) queries and mutations to enhance component. IMHO it's much more readable and powerfull than using query/mutaions components.

You can pass queried (filter) values as variables via data.fetchMore - of course you can use query component for 'inner query'.

Using cache directly isn't required while query 'cache-first' fetchPolicy option can be used.

xadm
  • 8,219
  • 3
  • 14
  • 25
  • Thank you, this is very helpful. After a bit of research I totally agree with you that the composition is a way to go. Would you be able to enhance your answer with example on how to use `data.fetchMore`? Using `GET_FILTERS` and `GET_POSTS` queries, where `GET_POSTS` takes a variable `filters`, with `compose` and `graphql` rendering arbitrary component `Posts`? – Kocur4d Oct 21 '18 at 09:18
  • 1
    I found many good inspirations in [apollo-universal-starter-kit](https://github.com/sysgears/apollo-universal-starter-kit/blob/56638f226abe0afefba333600e92784d10bb00ca/packages/client/src/modules/post/containers/Post.jsx) – xadm Oct 22 '18 at 12:42