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

Troubleshooting unique year values query in Next.js Sanity project.

16 replies
Last updated: Apr 26, 2023
Is it possible to get unique years value only from date time field across all documents of certain type? I have this query
{"uniqueYears": array::unique(

*[_type in ["event", "exhibition"] && defined(endDate)][].endDate

)}
but it returns the unique full dates.

0:"2018-01-06T12:30:00.000Z"

1:"2018-01-13T08:00:00.000Z"
Tried adding
| split("-")[0]
in the end of the query, but it’s not supported.
Apr 26, 2023, 1:36 PM
Basically get an array of [‘2023’,‘2022’,…‘2004’]
Apr 26, 2023, 1:39 PM
array::unique(
  *[_type in ["event", "exhibition"] && defined(endDate)]{
    "endDate": string::split(endDate, '-')[0]
  }.endDate
)

☝️ Try that?
Apr 26, 2023, 2:09 PM
Was just about to write i figured the query,
{

"uniqueYears": array::unique(

*[_type in ["event", "exhibition"] && defined(endDate)]{

'yearOnly': string::split(endDate, "-")[0],

}[].yearOnly

)

}
Apr 26, 2023, 2:19 PM
But nextjs is not happy with the query 😄
ClientError: expected '}' following object body
Apr 26, 2023, 2:22 PM
Does it work if you normalize the quotation marks in the query? Not sure if that’s a red herring .
Apr 26, 2023, 2:25 PM
Sounds like the query escaped at the wrong place or something
Apr 26, 2023, 2:26 PM
For some reason not
Apr 26, 2023, 2:27 PM
Does it work if you don’t wrap the query in an object?
Apr 26, 2023, 2:30 PM
array::unique(
      *[_type in ["event", "exhibition"] && defined(endDate)]{
        'yearOnly': string::split(endDate, "-")[0],
      }[].yearOnly
    )

Apr 26, 2023, 2:31 PM
Now it’s confused,
ClientError: unable to parse entire expression
Apr 26, 2023, 2:34 PM
Sounds like there is a character error somewhere
Apr 26, 2023, 2:35 PM
im using next-sanity. weirdly in Vision it returns the right output
Apr 26, 2023, 2:35 PM
“result”:*{*_1 item_“uniqueYears”:*[*_6 items_
0:“2019”
1:“2018"
2:“2021”
3:“2022"
4:“2023”
5:“2020"

]
}
Apr 26, 2023, 2:36 PM
user Y
Issue is next-sanity version. Project is using
"next-sanity": "0.6.0"
and just tested on an other project using
"next-sanity": "^4.1.7"
and works as expected!!
User, thanks for looking into this
Apr 26, 2023, 2:47 PM
Aha! Great!
Apr 26, 2023, 2:51 PM
This opens a can of worms now 🤦
Apr 26, 2023, 2:52 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?