How to use an array inside a GraphQL Query Variable
Asked Answered
M

1

9

I'd like to use an array inside a GraphQL query variable so that I can get the data of more than one product from a single query with Gatsby however at the moment I get errors.

My graphQL query looks like:

query ($id: [String!]) {
  shopifyProduct(handle: {eq: $id}) {
    handle
    id
    title
    handle
    productType
    shopifyId
  }
}

and my Query Variable looks like:

{
  "id": ["liner-jacket", "pocket-t-shirt"]
}

The desired response would be (something like):

{
  "data": {
    "shopifyProduct": {
      "handle": "liner-jacket",
      "id": "Shopify__Product__hopbjidjoqjndadnawdawda123123=",
      "title": "Liner Jacket",
      "productType": "jacket",
      "shopifyId": "hopbjidjoqjndadnawdawda123123="
    },
    "shopifyProduct": {
      "handle": "pocket-t-shirt",
      "id": "Shopify__Product__iajwdoiajdoadjwaowda4023123=",
      "title": "Pocket T-Shirt",
      "productType": "t-shirt",
      "shopifyId": "iajwdoiajdoadjwaowda4023123="
    }
  }
}
Madewell answered 22/9, 2019 at 14:50 Comment(0)
U
12

GraphQL supports a special List type that represents an array of a particular type. For example, [String] is a List of the type String. Even though the [String] type wraps String, in GraphQL it is considered a separate, distinct type from String. In other words, you can't use [String] where String is expected and you can't use String where [String] is expected.

An argument (like handle) or input object field (like eq) only has a single GraphQL type. If a variable is used as the value of an argument, its type must match that argument's type. It appears eq has the type String! (a non-null String), so you can only pass it a single String, not a List.

Whether a way exists to query based on an array of values is up to the server implementation. Some schemas support a way to do that (for example, instead of eq, there may be an in field that accepts a List). However, this is schema-specific. Review the document for the server/framework/library you're using, or explore the schema using an available GraphiQL or GraphQL Playground interface.

Unguinous answered 22/9, 2019 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.