2

Using apollo-client and graphql-tag I'm trying to create a request something like:

gql`
    {
        data(
            filter: ${options.filter}
            sort: ${options.sort}
            limit: ${options.limit}
            offset: ${options.offset}
        ) {
            name
        }
    }
`

However not all of these options are always set, sometimes I might only use limit and offset. But if I leave them unset I get Expected type Int, found undefined.

Should I loop through my options object beforehand and swap any undefined values with null? Or is there a better way to structure this?

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
joshhunt
  • 5,197
  • 4
  • 37
  • 60

1 Answers1

4

You should avoid using placeholders for values inside your query and use variables instead. So your query would now look like something like this:

const MY_QUERY = gql`
  query MyQuery($filter: String, $sort: String, $limit: Int, $offset: Int) {
    data (
      filter: $filter
      sort: $sort
      limit: $limit
      offset: $offset
    ) {
      name
    }
  }
`

Note: the types you define for your variables will need to match whatever your schema is for the filter, sort, limit and offset arguments.

Now you can pass in the variables when rendering your Query component:

<Query query={MY_QUERY} variables={{ limit: 10, offset: 20 }}>
  {({ loading, error, data }) => {
    // ...
  }}
</Query>

Or, using the HOC:

graphql(MY_QUERY, { options: (props) => ({ variables: { limit: 10, offset: 20 } }) }

Or using the client directly:

client.query({ query: MY_QUERY, variables: { limit: 10, offset: 20 } })

If any of the variables are undefined, they'll be ignored without you having to do anything more.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Ah thanks, definitely looks like I missed something so will go do some more reading. We currently don't use any of the supported view libraries (react, angular etc) so sometimes it is a bit hard to figure out the examples. What does HOC stand for? – joshhunt May 09 '18 at 00:31
  • Sorry, I have a bad tendency to assume everyone uses React :P HOC stands for Higher Order Component and is a React concept. I've edited my answer to include an example how to use variables when using the client directly. See the docs for more details: https://www.apollographql.com/docs/react/api/apollo-client.html#ApolloClient.query – Daniel Rearden May 09 '18 at 00:40
  • Thanks, it makes a lot more sense now. Lol it took me a looong time to figure out that I don't have to add the type to the client as well, e.g. I have a server enum DataSort and I was trying to add the enum to my query so I could add it in `query MyQuery(...)`... Eventually https://github.com/apollographql/apollo-client/issues/636 pointed me in the right direction – joshhunt May 09 '18 at 02:46