GraphQL Fragments

Fragments is also a very important concept in GraphQL. This is used to group re-usable code together.

To get a basic understanding about this, read the below blog post its very simple and easy to understand

https://medium.com/graphql-mastery/graphql-fragments-and-how-to-use-them-8ee30b44f59e

Let’s see how we can us it in our todo application.

In our app all queries, mutations are using these fields

    id,
    task,
    isComplete

We can easily reuse this in our app like this

import gql from "graphql-tag";


export const TODO_FRAGMENT = `

fragment todoFields on Todo {
    id,
    task,
    isComplete
}

`

export const GET_TODO = gql`
query getTodo {
  todos {
    ...todoFields
  }
}
${TODO_FRAGMENT}
`
import gql from "graphql-tag";

import { TODO_FRAGMENT } from "./query"

export const UPDATE_TODO = gql`
mutation updateTodo($id: ID!, $task: String, $isComplete: Boolean){
  updateTodo(
input: {
  id: $id,
  task : $task,
  isComplete: $isComplete
}
  ){
    ...todoFields
  }
}
${TODO_FRAGMENT}
`

export const ADD_TODO = gql`
  mutation addTodo($task: String!) {
  addTodo(input: { task: $task, isComplete: false }) {
    ...todoFields
  }
}
${TODO_FRAGMENT}
`

This is the whole purpose of fragments, to reuse query elements.

Fragments can be used for many more things, but this is the basic concept of a fragment

This is how our todo app looks now

https://github.com/reactexcel/graphql-todo/commit/c08f811508c394812eaac85a20a9dd983a51bead

Fragments is a frontend only concept!

Read more in details about fragments here https://www.apollographql.com/docs/react/advanced/fragments.html

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype