React-apollo: Passing components state to query variables

Created on 18 Jan 2018  路  4Comments  路  Source: apollographql/react-apollo

Hi guys,
Is it possible to somehow inject components state into the query ?
Something like with props ?

options: (ownProps : any, ownState???) =>{
        console.log(a)
        return {
            variables: {
                name : ownProps.name
                id:  ownState.id <-------------------------

            }

Most helpful comment

I believe what you're looking for is this.props.data.refetch( variables ).

You don't want to inject the entire component state. What you do want is to be able to re-execute a GQL query, using variable inputs derived from component state.

refetch is available if your component is bound to a single GQL query like so:

graphql( gqlQueryString, config )( MyComponent )

When you invoke this.props.data.refetch, the argument you pass it will automatically replace any variables in the graphql config.

By contrast, if your component is bound to several GQL queries via react-apollo's compose function, then you can set options.name on each query, and then each of those queries will be exposed to the component as this.props[ ${options.name} ]. You can invoke them, and pass a whole new config.options object, like so:

this.props.aNamedQuery({ variables: { q: this.state.searchText }})

All 4 comments

If id tends to change, you can do a refetch with the new variables on each change.

If it's only set once and doesn't change within the life-cycle of that component , you might want to consider performing the query in an inner component instead and just feed it the id as a prop so you can use ownProps there.

I also had this same problem with a use case of trying to validate whether a username has already been taken, it needs to query pretty frequently. I would love to be able to access the state instead of creating wrapper components.

I believe what you're looking for is this.props.data.refetch( variables ).

You don't want to inject the entire component state. What you do want is to be able to re-execute a GQL query, using variable inputs derived from component state.

refetch is available if your component is bound to a single GQL query like so:

graphql( gqlQueryString, config )( MyComponent )

When you invoke this.props.data.refetch, the argument you pass it will automatically replace any variables in the graphql config.

By contrast, if your component is bound to several GQL queries via react-apollo's compose function, then you can set options.name on each query, and then each of those queries will be exposed to the component as this.props[ ${options.name} ]. You can invoke them, and pass a whole new config.options object, like so:

this.props.aNamedQuery({ variables: { q: this.state.searchText }})

Using variables is the correct way to inject client state into a query.

Was this page helpful?
0 / 5 - 0 ratings