Are you using Fragments in GraphQL?

πŸ€”  Have you been thinking about learning to use fragments? Well, here is the simplest description with demo.πŸŽ“

When we need to use/repeat the same fields in multiple queries, making changes can be tedious as we would have to update at all places.😬 This is where fragments come in handy πŸ’‘

A Fragment is a piece of code or logic that can be shared between multiple queries and mutations.

Lets take a look at the two queries for getting categories and products: ( using wp-graphql )

You will notice that we have to repeat the image fields in both of the queries ( for categories and products ).

Lets create a fragment for image called ImageFragment . Here we use the keyword fragment , ImageFragment is the name chosen by us.

const ImageFragment = `
fragment ImageFragment on WpMediaItem {
	  id
	  altText
	  caption
	  sourceUrl
	  mediaDetails {
	    sizes {
	      height
	      width
	      name
	      sourceUrl
	    }
	  }
}
`;

module.exports.ImageFragment = ImageFragment;

Here WpMediaItem is the type. If you are wondering how to get the type

You can use the Doc section of the Graphiql, and search for the query, and then as shown in the gif find the type of the field.

The last thing we do is use this fragment like so: ( assuming we are using it in common js file )

const { ImageFragment } = require('./fragments/image/index.js');

// Get all the front page data.
const GET_FRONT_PAGE = `
query GET_FRONT_PAGE {
  categories: allWpProductCategory(limit: 5) {
    nodes {
      id
      slug
      image {
        ...ImageFragment
      }
    }
  }
  products: allWpProduct(limit: 100) {
    edges {
      node {
      id
      name
      image {
        ...ImageFragment
      }
      }
    }
  }
}
${ ImageFragment }
`;

So you can see that we can reuse the same piece of logic in both queries and if we did have to make any changes in the query fields, we would only need to do it at one place in Fragment and it will be auto updated everywhere its used

Remember that you can only replace the fields of a type, so you cannot write like so:

  categories: allWpProductCategory(limit: 5) {
    nodes {
      id
      slug
       ...ImageFragment
    }
  }

Since we have added a fragment on image of type WPMediaItem hence we can use it like : image { ....ImageFragment }

You can take an example of my Github repo

That’s all folks hope you find it useful to use it in your next project.

One thought on “Are you using Fragments in GraphQL?

Leave a Reply