How can I get previous and next post in Strapi?

I dont know it’s the best solution but I found a way to get Previous and Next post with Strapi GraphQL by publishedAt

My queries are:

export const GET_NEXT_POST = gql`
  query GetNextPost($publishedAt: DateTime, $locale: I18NLocaleCode) {
    posts(
      filters: { publishedAt: { lt: $publishedAt } }
      locale: $locale
      sort: "publishedAt:desc"
      pagination: { limit: 1 }
    ) {
      data {
        attributes {
          Title
          Slug
          publishedAt
        }
      }
    }
  }
`;
export const GET_PREVIOUS_POST = gql`
  query GetPreviousPost($publishedAt: DateTime, $locale: I18NLocaleCode) {
    posts(
      filters: { publishedAt: { gt: $publishedAt } }
      locale: $locale
      sort: "publishedAt:asc"
      pagination: { limit: 1 }
    ) {
      data {
        attributes {
          Title
          Slug
          publishedAt
        }
      }
    }
  }
`;

In react component there is 2 another useQuery and useState for both

const [nextPost, setNextPost] = useState<any>(null);
const [previousPost, setPreviousPost] = useState<any>(null);
const { data: nextPostData } = useQuery(GET_NEXT_POST, {
    variables: {
      publishedAt: post?.publishedAt,
      locale,
    },
    fetchPolicy: "network-only",
    onCompleted: (data) => {
      setNextPost(data?.posts?.data[0]?.attributes);
    },
  });

  const { data: previousPostData } = useQuery(GET_PREVIOUS_POST, {
    variables: {
      publishedAt: post?.publishedAt,
      locale,
    },
    fetchPolicy: "network-only",
    onCompleted: (data) => {
      setPreviousPost(data?.posts?.data[0]?.attributes);
    },
  });

Of course there is little bit repeating code but you can make it more rebust. I want to share the logic. I hope helps someone.

@andreasoikon Thank you again to interest. :v: