How to execute a dynamic query in deskStructure every time in Sanity.io.

2 replies
Last updated: Oct 27, 2023
In the deskStructure, I have a `S.documentList('page').title('All Pages').filter(
_type == 'page' && ${dynamicQuery()}
)` The
dynamicQuery()
call could change the query each time.
Is there any way to get the deskStructure to execute it every time, rather than caching ahead of time and running the same query? I can see that having in
child()
a
context.documentStore.listenQuery
executes every time, it'd be great if I could pipe that into the documentList. I'm trying to avoid a hacky solution that uses listenQuery and just ignores the response so that
S.documentList
gets executed every time.
Oct 27, 2023, 12:50 PM
I've managed to find a way through creating an Observable, but it'd be great to know if there's a better way:

.child(new Observable((subscriber) => {
             subscriber.next(dynamicQuery())
            }).pipe(map((groqQuery) => {
                return S.documentList('page')
                  .title('All Pages')
                  .menuItems(S.documentTypeList('page').getMenuItems())
                  .filter(`_type == "page" && ${groqQuery}`)
            })))

Oct 27, 2023, 1:42 PM
I've actually created an elegant solution from this. abstracting the Observable away from here, creating a wrapper `getDynamicQuery((query) => S.documentList('page').filter(
_type == 'page' ${query}
)` .
In my case, the dynamic query is based off of localStorage. So in
getDynamicQuery
I create an
Observable
and the
subscriber
to an array. Then, there's a global
window.addEventListener('storage', event => { ... })
that loops through the callback array and calls
subscriber.next(...)
with the query based off of the updated storage value.
All open tabs then update when the value is changed, so there are no inconsistencies or confusing behaviour.
Oct 27, 2023, 4:12 PM

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?