Skip to content

Custom query fetching keys #1208

@hajiskyy

Description

@hajiskyy

Is your feature request related to a problem? Please describe.

We use sanity in production, our pages, components etc. are all specd and controlled through sanity. As you can imagine, there are some times when I need to use some data across multiple components and to prevent fetching data multiple times, i have had to use the useAsyncData composable and the client fetch to have defined keys and useNuxtData to get the keyed data elsewhere when needed. This is fine, until I tried to implement the visual editing, now it says that i need to use the useSanityQuery to fetch data. Problem with that is, I can't define what the keys are going to be. i understand that, at the moment, the keys are randomly generated per request :(

Describe the solution you'd like to see

Is it possible to work towards allowing optional keys for useSanityQuery?, I can see that its options are an extension of the useAsyncData type. perhaps we could start from there and maybe add a key option, extract and/or overwrite the key if does/doesn't exist.

interface UseSanityQueryOptions<T> extends AsyncDataOptions<T> {
client?: string
}
export const useSanityQuery = <T = unknown, E = Error> (query: string, _params?: Record<string, unknown>, _options: UseSanityQueryOptions<T> = {}): AsyncData<T | null, E> => {
const { client, ...options } = _options
const sanity = useSanity(client)
const params = _params ? reactive(_params) : undefined
if (params) {
options.watch = options.watch || []
options.watch.push(params)
}
return useAsyncData('sanity-' + hash(query + (params ? JSON.stringify(params) : '')), () => sanity.fetch<T>(query, params || {}), options) as AsyncData<T | null, E>
}

Describe alternatives you've considered

If it's not possible, is there some recommended approach to make this work?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions