React-apollo: Include `variables` in query props

Created on 9 Jun 2016  路  5Comments  路  Source: apollographql/react-apollo

There's currently no way to access variables inside a component wrapped with connect.

It would be great if variables passed to queries in connect() were also passed as a query prop.

E.g:


import React from 'react'

import gql from 'apollo-client/gql'
import { connect } from 'react-apollo'

const MyComponent = { myQuery } => {
  const { items = [], variables, loading, refetch } = myQuery
  const loadMore = () => refetch({
    ...variables,
    skip: variables.skip + variables.limit
  })

  return (
    <div>
      {items.map(item => <div key={item.id}>{item.text}</div>)}

      <button onClick={loadMore}>Load more</button>
    </div>
  )
}

export default connect({
  mapQueriesToProps() {
    return {
      myQuery: {
        query: gql`
          query (
            $limit: Int
            $skip: String
          ) {
            items(
              limit: $limit
              skip: $skip
            ) {
              id
              text
            }
          }
        `,
        variables: {
          limit: 10,
          skip: 0,
        },
      },
    }
  },
})(MyComponent)
question

Most helpful comment

I have been looking around and couldn't find the way to pass the variables through the components state. Can anyone help me with that?
Thanks

All 5 comments

@simenbrekken Is there a good reason for not setting the variables through props? In my opinion variables should always be set through props or state, otherwise your components are going to be difficult to understand and maintain.

@simenbrekken I think this could be valuable for merging / using original props in refetch methods. I'll add it in the 1.0

I have been looking around and couldn't find the way to pass the variables through the components state. Can anyone help me with that?
Thanks

Anyone with an idea how to pass the variables through the components state?? I'm stuck with the same problem than @mukkachaitanya

@ElNinjaGaiden @mukkachaitanya

The way I did it (Probably a terrible idea) is to use Redux for a single app wide state and then store the variable I want to change in the Redux Store. Then when I had a component that needed a component a prop variable I would pass it the Redux state reference. Then inside the component I gave it access to the action to change the the Redux state. If that makes sense.

If someone has a simpler and more elegent way of doing this please share.

Was this page helpful?
0 / 5 - 0 ratings