Search code examples
reactjsgraphqlapollo-client

Reactive variables as query parameters


After implementing apollo-client into my react app, I noticed that a lot of input data will probably end up in a reactive variable somewhere. And if I want to request anything to the server, often, the value will come from a reactive variable. So it would simplify my code a lot if I could link the value of the reactive variable to the parameters of my query. Ideally, what I would want is something like this:

gql`
query FirstName {
  firstName @client
}
query LastName {
  lastName @client
}

query user($firstName: ???, $lastName: ???){
  user(firstName: $firstName, lastName: $lastName){
    id
    firstName
    lastName
    address
    dob
  }
}
`

Now, I understand that these requests would resolve in parallel, so the above would never work... But, how do I make it work? Do I need to add loadash just for this? Is there an apollo-client solution for this? How would I solve this with loadash or any other library?


Solution

  • What you're looking for is the @export directive, this section of the docs explains how to use the local state as variables.

    Your query would look like this

    query user($firstName: ???, $lastName: ???){
      firstName @client @export(as: "firstName")
      lastName @client @export(as: "lastName")
      user(firstName: $firstName, lastName: $lastName){
        id
        firstName
        lastName
        address
        dob
      }
    }