Marc Greenstock
Marc Greenstock

Reputation: 11688

Is it possible to use nested / namespaced query variables in a GraphQL query?

I'd like to namespace / nest query variables like this:

query ($params: {$id: ID!}) {
  getUser(id: $params.id) {
    email
    username
  }
}

with the variables:

{
  "params": {
    "id": "42"
  }
}

but it's not a valid query.

However a query like:

query ($id: ID!) {
  getUser(id: $id) {
    email
    username
  }
}

with the variables:

{
  "id": "42"
}

will work just fine.

The reason I want to do this is to automatically send in query options into the ApolloReact graphql higher order component with the params prop from that is applied to the wrapped component from react router. This question essentially has nothing to do with react router, apart from the fact that the params prop is applied to the component by react router.

ApolloReact will try to use the props from the component to automatically build the variables object, and since id is nested in props it can't find it.

The alternative is to specifically define where to find id, by defining an options method that receives ownProps and returns the variables object in graphql but I would like to avoid it if possible.

Upvotes: 2

Views: 1169

Answers (1)

davidyaha
davidyaha

Reputation: 1960

No, you can't use the fields of that composite type in the query.

I think your best option will be to create the following function:

const options = ({params: variables}) => ({variables})

and export the wrapped component like so:

export default graphql(QUERY, {options})(Component)

That way the params property passed by react-router will become the variables object passed to the query and you can use it like this:

<Component id="1" otherVar="some value"/>

With the regular query:

query ($id: ID!) {
  getUser(id: $id) {
    email
    username
  }
}

Upvotes: 3

Related Questions