Search code examples
graphqlgatsbycontentful

Sorting GraphQL query on multiple queries in Gatsby


I'm using Gatsby as my static generator and Contentful as my datasource.

We've got multiple contentTypes in Contentful (blog, event, whitepaper) and I want to return these in within one query and sorted by createdAt date. So far I have the following which returns each contentType in order of each contentType but not in order of date overall.

Is there a way I can do a sort across the entire query?

{
    whitepapers: allContentfulWhitepaper(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
        }
      }
    }
    blogs: allContentfulBlogPost(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
        }
      }
    }
    events: allContentfulEventPage(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
        }
      }
    }
  }

Solution

  • I don't think GraphQL query is able to do the sorting across multiple fields, but you can sort in component

    import React from 'react';
    import { graphql } from 'gatsby';
    
    const IndexPage = ({ data }) => {
      const { whitepapers, blogs, events } = data;
      const allDataInDesc = [
        ...whitepagers.edges.map(e => e.node),
        ...blogs.edges.map(e => e.node),
        ...events.edges.map(e => e.node),
      ].sort((a, b) => { return new Date(a.createdAt) > new Date(b.createdAt) ? -1 : 1; });
    
      return <>...</>
    }
    
    export const query = graphql`
      {
        whitepapers: allContentfulWhitepaper(sort: { order: DESC, fields: createdAt }) {
          edges {
            node {
              id
              slug
              title
              createdAt
            }
          }
        }
        blogs: allContentfulBlogPost(sort: { order: DESC, fields: createdAt }) {
          edges {
            node {
              id
              slug
              title
              createdAt
            }
          }
        }
        events: allContentfulEventPage(sort: { order: DESC, fields: createdAt }) {
          edges {
            node {
              id
              slug
              title
              createdAt
            }
          }
        }
      }
    `;
    
    export default IndexPage;