javascriptsanitygroq

How to query the next post with GROQ sanity


I want to fetch the data for the next post in order they were created at - currently nextPost returns null

`*[_type == "project" && _createdAt > ^._createdAt] | order(_createdAt asc)[0]{
    _createdAt,
    'slug': slug.current,
  }`,

Full Fetch Function

export async function getPostAndMorePosts(slug, preview) {
const curClient = getClient(preview)
const [post, nextPost] = await Promise.all([
curClient
    .fetch(
        `*[_type == "project" && slug.current == $slug] | order(_createdAt desc) {
            _createdAt,
           'slug': slug.current,
      }`,
        { slug }
      )
      .then((res) => res?.[0]),
    curClient.fetch(
      `*[_type == "project" && _createdAt > ^._createdAt] | order(_createdAt asc)[0]{
         _createdAt,
         'slug': slug.current,
      }`,
      { slug }
    ),
  ])

  return { post, nextPost }
}

Solution

  • You can try with the following query:

    const query = `*[_type == "project" && slug.current == $slug][0] {
      "currentProject": {
        // Fields
      },
      "nextProject": *[_type == "project" && ^._createdAt < _createdAt] | order(_createdAt asc)[0] {
       // Fields
      }
    }`
    
    const { currentProject, nextProject } = await curClient.fetch(query, { slug })