react-apollo icon indicating copy to clipboard operation
react-apollo copied to clipboard

Include `variables` in query props

Open simenbrekken opened this issue 10 years ago • 5 comments

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)

simenbrekken avatar Jun 09 '16 12:06 simenbrekken

@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.

helfer avatar Jun 09 '16 15:06 helfer

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

jbaxleyiii avatar Aug 02 '16 02:08 jbaxleyiii

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

mukkachaitanya avatar Jun 29 '17 11:06 mukkachaitanya

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

ElNinjaGaiden avatar Oct 07 '17 18:10 ElNinjaGaiden

@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.

Aspintyl000 avatar Dec 21 '17 03:12 Aspintyl000