Giedrius
Giedrius

Reputation: 613

Forming a single query requested by multiple components

I am thinking to move to graphQL from a standard REST API architecture. Currently I have a data wrapper which preloads a dataset after initialization with user info, and other meta data.

Is there a way for apollo client to build a single query requested by multiple components and send it to graphQL server after the components are loaded instead of sending separate queries for each component and form a data layer that is necessary for application to operate ?

What are the possibilities eventually other options to do this and make it better with GraphQL then the current implementation.

Upvotes: 0

Views: 1141

Answers (2)

Rami Enbashi
Rami Enbashi

Reputation: 3556

Queries in Apollo client have an option fetchPolicy with default value cache-first which means Apollo will try to read from your local cache first before attempting a network fetch. If you have multiple components requesting data that has been fetched already then no network calls will happen. Just ensure to return the id field of the requested data in your query even if your component doesn't use it to ensure proper caching.

Upvotes: 1

Aliaksei Maniuk
Aliaksei Maniuk

Reputation: 1664

Let's assume you have the following graphql schema:

type Query {
    question(questionId: Int!): Question
    tag(tagId: Int!): Tag
}

type Question {
    questionId: Int!
    content: String!
}

type Tag {
    tagId: Int!
    tagName: String!
}

If you want to retrieve 2 objects in one request you can write the following qraphql request:

{
  question(questionId: 1) {
    questionId
    content
  }
  tag(tagId:1){
    tagId
    tagName
  }
}

As output, you will receive the following JSON:

{
  "data": {
    "question": {
      "questionId": 1,
      "content": "how to code in js?"
    },
    "tag": {
      "tagId": 1,
      "tagName": "js"
    }
  }
}

Upvotes: 0

Related Questions