Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

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– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?