0

I'd like to be able to dynamically choose which query variables I use in GraphQL.

For example, it seems a little redundant to need three separate queries:

const getAllStops = gql`
  query trafficStops {
    trafficStops {
      id
      date
    }
  }
`

const getStopsAfter = gql`
  query trafficStops($after: String!) {
    trafficStops(after: $after) {
      id
      date
    }
  }
`
const getStopsBefore = gql`
  query trafficStops($before: String!) {
    trafficStops(before: $before) {
      id
      date
    }
  }
`

Is there a way in which I could pass not just the variables before or after but whether I'd like to use one, the other, neither, or both into a single query instead of having multiple queries?

1 Answer 1

2

Yes, you just have to make your arguments optional. The exclamation mark at String! requires the argument to be a string and not null. Hence, by removing it you could write your single query as

const getAllStops = gql`
  query trafficStops($after: String, $before: String)  {
    trafficStops(after: $after, before: $before) {
      id
      date
    }
  }
`
Sign up to request clarification or add additional context in comments.

1 Comment

You know, I'd had it set up this way on the server and it didn't even occur to me to do it on the frontend. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.