usertirex
usertirex

Reputation: 15

How to do order by `createdAt` in my GraphQl query?

I want to return the oNewest posts to oldest.

This is my query:

export const getPosts = async () => {
  const query = gql `
    query MyQuery {
      postsConnection {
        edges {
          cursor
          node {
            author {
              bio
              name
              id
              photo {
                url
              }
            }
            createdAt
            slug
            title
            excerpt
            featuredImage {
              url
            }
            categories {
              name
              slug
            }
          }
        }
      }
    }
  `;
  const result = await request(graphqlAPI, query);

  return result.postsConnection.edges;
};

Upvotes: 1

Views: 2309

Answers (1)

gru
gru

Reputation: 3069

You can use the following syntax:

postsConnection (sort: "createdAt:desc") {

Full example:

export const getPosts = async () => {
  const query = gql `
    query MyQuery {
      postsConnection (sort: "createdAt:desc") {
        edges {
          cursor
          node {
            author {
              bio
              name
              id
              photo {
                url
              }
            }
            createdAt
            slug
            title
            excerpt
            featuredImage {
              url
            }
            categories {
              name
              slug
            }
          }
        }
      }
    }
  `;
  const result = await request(graphqlAPI, query);

  return result.postsConnection.edges;
};

Upvotes: 2

Related Questions