2

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.

Marc Greenstock
  • 11,278
  • 4
  • 30
  • 54

1 Answers1

3

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
  }
}
davidyaha
  • 1,940
  • 1
  • 12
  • 5
  • Thanks for your answer, I'm not trying to use an input that holds everything, rather I'm trying to leverage the default functionality that Apollo React provides: "By default, graphql will attempt to pick up any missing variables from the query from ownProps". – Marc Greenstock Oct 11 '16 at 08:08
  • Sure! removed that part and added the actual result that you wanted so it would make more sense. – davidyaha Oct 12 '16 at 14:09