10

Can I fetch more than one element in a GraphQL query? I have many products list data and I want to fetch, for example, three products in my component. I have an array of needed product IDs, can I pass it to query? This is my query for one product:

query ProductInCartQuery($id: ID!){
  Product(id: $id) { 
   id
   name
   price
 }
}

But I don't think I can just put it in a function and execute it for example three times for three products.

marktani
  • 7,578
  • 6
  • 37
  • 60
Alan Wołejko
  • 442
  • 2
  • 5
  • 20

2 Answers2

14

It's common and very useful to offer two kind of queries for every type you have:

  1. a query to fetch a single node with an id or other unique fields, that's in your case Product (you already have this).

  2. a query to fetch many nodes depending on different filter conditions, let's call it allProducts.

Then you have two options to fetch multiple products in one query.

First, you can use the Product query multiple times and use GraphQL Aliases to avoid a name clash in the response data:

query ProductInCartQuery($firstId: ID!, $secondId: ID!){
  firstProduct: Product(id: $firstId) { 
    id
    ... ProductInfo
  }

  secondProduct: Product(id: $secondId) { 
    id
    ... ProductInfo
  }

  fragment ProductInfo on Product {
    name
    price
  }
} 

You could build this query string dynamically depending on the ids you want to query. However, it's probably best to use the allProducts query with the necessary filter setup if the number of differents ids is dynamic:

query filteredProducts($ids: [ID!]!) {
  allProducts(filter: {
    id_in: $ids
  }) {
    ... ProductInfo
  }
}

fragment ProductInfo on Product {
  name
  price
}

You can try it out yourself in this GraphQL Playground I prepared for you. More background information can be found in this article.

marktani
  • 7,578
  • 6
  • 37
  • 60
2

For adding the product ids to the query you could define a input type. See the cheat sheet.

So the query on the client could look like:

query ProductsInCartQuery($productIds: ProductIds!) {
  Products(productIds: $productIds) {
    id
    name
    price
  }
}

On the server you define the schema with the input type as follows:

input ProductIds {
  ids: [ID!]
}

type Query {
  Products(productIds: ProductIds!) {
    id
    name
    price
  }
}

schema {
  query: Query
}
Locco0_0
  • 3,420
  • 5
  • 30
  • 42