Structured Content 2022: Join our conference to explore fresh perspectives on content and digital experiences →

Is there a way to write a groq query that checks if a boolean is true, and if so, returns an array of referenced documents? (example use case, on a homepage, I want to allow...

7 replies
Last updated: Feb 1, 2021

Is there a way to write a groq query that checks if a boolean is true, and if so, returns an array of referenced documents? (example use case, on a homepage, I want to allow the client to enable/disable showing the 3 most recent blog posts)I have this, but it doesn’t work

{ features[_type match 'blogEntries'] { 'posts' : *[_type == 'post'][0..2] { ... } } }

Feb 1, 2021, 5:50 PM

I think I got it

{
  "posts": *[_type == 'post' && 'blogEntries' in (^.features[]._type)][0..2],	
} 

Feb 1, 2021, 6:08 PM

I guess the question now is, can I modify the limit based on a field value. Ie, inside of ‘blogEntries’ if I set the query to return 5 instead of three, can I make that range at the end become [0..4] ?

Feb 1, 2021, 6:15 PM

If you pass the end number as a parameter, you could replace

[0..2]
with something like
[0..$num]
.

Feb 1, 2021, 6:24 PM

Could $num somehow be referenced from the query response

Feb 1, 2021, 6:35 PM

Yes, $num would be a query parameter that you could pass through the URI, as props, or even pulling from a document containing the ranges.

Feb 1, 2021, 6:51 PM

Here’s an example:

export async function getAllStaff(num) {
  const result = await client.fetch(
    `*[_type == "staff"] | order(firstName asc, lastName asc) {
      firstName,
      lastName,
      slug,
      image,
      position,
      _type,
    }[0..${num}]`
  );

  return result;
}
Then I’m calling the function from getStaticProps and passing in `num`:


export async function getStaticProps() {
  const allStaff = await getAllStaff(8);

  return {
    props: { allStaff },
    revalidate: 120,
  };
}

Feb 1, 2021, 7:22 PM

Thanks

user A
, that looks great

Feb 1, 2021, 7:25 PM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.