API Documentation / @pinia/colada / defineQuery
Function: defineQuery()
Call Signature
ts
function defineQuery<TResult, TError>(options): () => UseQueryReturn<TResult, TError>
Define a query with the given options. Similar to useQuery(options)
but allows you to reuse the query in multiple places. It only allow static values in options. If you need dynamic values, use the function version.
Type Parameters
TResult
TResult
TError
TError
= { custom
: Error
; }
Parameters
options
DefineQueryOptions
<TResult
, TError
>
the options to define the query
Returns
Function
Returns
UseQueryReturn
<TResult
, TError
>
Example
ts
const useTodoList = defineQuery({
key: ['todos'],
query: () => fetch('/api/todos', { method: 'GET' }),
})
Call Signature
ts
function defineQuery<T>(setup): () => T
Define a query with a setup function. Allows to return arbitrary values from the query function, create contextual refs, rename the returned values, etc. The setup function will be called only once, like stores, and must be synchronous.
Type Parameters
T
T
Parameters
setup
() => T
a function to setup the query
Returns
Function
Returns
T
Example
ts
const useFilteredTodos = defineQuery(() => {
const todoFilter = ref<'all' | 'finished' | 'unfinished'>('all')
const { data, ...rest } = useQuery({
key: ['todos', { filter: todoFilter.value }],
query: () =>
fetch(`/api/todos?filter=${todoFilter.value}`, { method: 'GET' }),
})
// expose the todoFilter ref and rename data for convenience
return { ...rest, todoList: data, todoFilter }
})