Skip to content

API Documentation / @pinia/colada / defineQuery

Function: defineQuery() ​

Call Signature ​

ts
function defineQuery<TData, TError>(options): () => UseQueryReturn<TData, TError>;

Define a query with the given options. Similar to useQuery(options) but allows you to reuse all of the query state in multiple places. It only allow static values in options. If you need dynamic values, use the function version.

Type Parameters ​

TData ​

TData

TError ​

TError = { custom: Error; }

Parameters ​

options ​

DefineQueryOptions<TData, TError>

the options to define the query

Returns ​

() => UseQueryReturn<TData, 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 ​

() => 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 }
})

Released under the MIT License.