Open m4rrc0 opened 1 year ago
@m4rrc0 Did you ever end finding a workaround that let's you dynamically set orderBy
and orderDirection
on your sort function?
I'm have this exact same case and currently am stuck trying trying to get a dynamic asc
or desc
sort working in a single query. Our project makes heavy use of the new typegen cli and string interpolation breaks the generation of types.
const listToolsQuery = groq`
*[_type == "tool"]
| order(
select(
$orderBy == "rank" => rank,
$orderBy == "_createdAt" => _createdAt
)
// How can I dynamically set 'asc' or 'desc' here from a parameter here?
)
{
"slug": slug.current,
"rank": rank,
_createdAt
}
`;
Further discussion here in the Sanity slack: https://sanity-io-land.slack.com/archives/C011CAT70DD/p1717972385870249
The conclusion here seems that this is not possible right now.
This would be a massive help for us and our project especially with the new launch of the sanity-typegen workflow. Splitting up our query and using string interpolation breaks typegen for this query. We'd really prefer to avoid losing type safety since this is a core query in our app.
I'm currently facing this same issue on a project I am working on. It would help greatly if we could parametrize the sort order while keeping type safety in this type of workflow.
I have been looking for a solution for this but it is apparently impossible (or at least very impractical; see below).
For example:
*[] | order($orderBy)
With params{ "orderBy": "createdAt"}
The only "not-really-a-solution" I found is this:
(context: I am using the plugin
sanity-plugin-documents-pane
and the Sanity studio crashed when trying to do the same forasc
)This is deeply impractical.
Improvements I can come up with:
*[] | order(unquote($orderBy))
*[] | order(@[$orderBy])
Or