Search code examples
node.jsgraphnext.jsreact-apollostrapi

Sorting in GraphQL by ID


I downloaded one simple tutorial code. But as I am playing with it I couldn't figure out how can I sort for example by id in graphql.

This is query.js

import React from "react";
import { useQuery } from "@apollo/react-hooks";

const Query = ({ children, query, id }) => {
  console.log(id);
  const { data, loading, error } = useQuery(query, {
    variables: { id: parseInt(id) }
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {JSON.stringify(error)}</p>;
  return children({ data });
};

export default Query;

Articles.js

    import gql from "graphql-tag";

    const ARTICLES_QUERY = gql`

  query Articles {
    articles(limit: 10) {
      id
      title
      category {
        id
        name
      }
      Image
    }
  }
`;

export default ARTICLES_QUERY;

And then calling it using one componnent.

  <Query query={ARTICLES_QUERY}>
    {({ data: { articles } }) => {
      return <Articles articles={articles} />;
    }}
  </Query>

I was able to limit number of results to 10 as you can see in code articles(limit: 10) but i cant figure out how can i see only last 10 items. (now its first 10). Thank for any help.


Solution

  • You will have to update the sort on the ID to fetch from the end

    query Articles {
        articles(limit: 10, sort: "id:desc") {
          id
          title
          category {
            id
            name
          }
          Image
        }
      }