### Define a query with a setup function Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineQuery.html Uses a setup function to return arbitrary values, create contextual refs, or rename returned values. The setup function must be synchronous. ```typescript 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 } }) ``` -------------------------------- ### defineQuery(setup) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineQuery.html Defines a query using a setup function, enabling the creation of contextual refs and custom return values. ```APIDOC ## defineQuery(setup) ### Description Define a query with a setup function. Allows returning arbitrary values from the query function, creating contextual refs, and renaming returned values. The setup function must be synchronous. ### Parameters - **setup** (() => T) - Required - A function to setup the query. ### Returns - **Function** - A function that 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' }), }) return { ...rest, todoList: data, todoFilter } }) ``` ``` -------------------------------- ### Install Pinia Colada package Source: https://pinia-colada.esm.dev/guide/installation.html Install the core library alongside Pinia using a package manager. ```bash # or pnpm, or yarn, etc npm i @pinia/colada ``` -------------------------------- ### defineMutation(setup) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineMutation.html Defines a mutation using a setup function, allowing for custom return values, contextual refs, and renaming of returned methods. ```APIDOC ## defineMutation(setup) ### Description Defines a mutation with a function setup. This allows you to return arbitrary values from the mutation function, create contextual refs, or rename returned values for convenience. ### Parameters - **setup** (Function) - Required - A function that sets up the mutation and returns the desired interface. ### Returns - **Function** - Returns a function that, when called, returns the value defined by the setup function. ### Example ```ts const useCreateTodo = defineMutation(() => { const todoText = ref('') const { data, mutate, ...rest } = useMutation({ mutation: () => fetch('/api/todos', { method: 'POST', body: JSON.stringify({ text: todoText.value }), }), }) return { ...rest, createTodo: mutate, todo: data, todoText } }) ``` ``` -------------------------------- ### Basic useQuery Usage Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/useQuery.html Example of initializing a query with a key and a fetch function. ```typescript const { state } = useQuery({ key: ['documents'], query: () => getDocuments(), }) ``` -------------------------------- ### Implement list and detail views with useQuery Source: https://pinia-colada.esm.dev/quick-start.html Examples demonstrating how to handle loading and error states in a list view and how to use dynamic keys for detail views based on route parameters. ```vue ``` ```vue ``` -------------------------------- ### Defining a Filtered Todo Query Source: https://pinia-colada.esm.dev/advanced/reusable-queries.html Example of a custom composable using defineQuery to share search state across multiple components. ```typescript import { defineQuery , useQuery } from '@pinia/colada' import { ref } from 'vue' export const useFilteredTodos = defineQuery (() => { // `search` is shared by all components using this query const search = ref ('') const { state , ... rest } = useQuery ({ key : () => ['todos', { search : search . value }], query : () => fetch (`/api/todos?filter=${ search . value }`, { method : 'GET' }), }) return { ... rest , // we can rename properties for convenience too todoList : state , search , } }) ``` -------------------------------- ### defineInfiniteQueryOptions(setupOptions) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineInfiniteQueryOptions.html Defines dynamic infinite query options by passing a function that accepts parameters and returns the query options, enabling type-safe dynamic query keys. ```APIDOC ## defineInfiniteQueryOptions(setupOptions) ### Description Defines dynamic infinite query options by providing a factory function. This allows the query configuration to depend on runtime parameters. ### Parameters - **setupOptions** (Function) - Required - A function that accepts parameters and returns a UseInfiniteQueryOptions object. ### Returns - **Function** - A function that accepts parameters and returns a DefineInfiniteQueryOptionsTagged object. ### Usage Pass the result to useInfiniteQuery: `useInfiniteQuery(() => setupOptions(params))`. ``` -------------------------------- ### Fetch data with useQuery Source: https://pinia-colada.esm.dev/quick-start.html Basic implementation of a query to fetch a product list using a static key. ```vue ``` -------------------------------- ### defineMutationOptions(setupOptions) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineMutationOptions.html Defines dynamic mutation options by passing a function that returns the mutation options, allowing for parameterization. ```APIDOC ## defineMutationOptions(setupOptions) ### Description Defines dynamic mutation options by passing a function that accepts an optional or required parameter and returns the mutation options. This is useful for creating factory functions for mutations. ### Parameters - **setupOptions** ((params?) => UseMutationOptions) - Required - A function that returns the mutation options based on provided parameters. ### Returns - **(params?) => DefineMutationOptionsTagged** - A function that, when called with parameters, returns the tagged mutation options. ``` -------------------------------- ### useInfiniteQuery(options) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/useInfiniteQuery.html Initializes an infinite query using a configuration object to manage paginated data. ```APIDOC ## useInfiniteQuery(options) ### Description Stores and merges paginated data into a single cache entry. This function is designed to handle infinite scrolling scenarios. ### Parameters - **options** (UseInfiniteQueryOptions) - Required - Configuration options for the infinite query. ### Returns - **UseInfiniteQueryReturn** - An object containing the state and methods to manage the infinite query. ``` -------------------------------- ### UseInfiniteQueryLoadMoreOptions Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseInfiniteQueryLoadMoreOptions.html Configuration options for loadNextPage and loadPreviousPage methods. ```APIDOC ## Interface: UseInfiniteQueryLoadMoreOptions ### Properties - **cancelRefetch** (boolean) - Optional - Whether to cancel an ongoing refetch when a new one is triggered. If set to false, a new load will be ignored if there's already one in progress. Default: true. - **throwOnError** (boolean) - Optional - Whether to throw an error if the fetch fails. Default: false. ``` -------------------------------- ### defineQueryOptions(setupOrOptions) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineQueryOptions.html Defines type-safe query options. Can be used for static options or dynamic options that accept parameters. ```APIDOC ## defineQueryOptions(setupOrOptions) ### Description Defines type-safe query options for use with Pinia Colada. It supports static options or dynamic functions that accept parameters to generate query keys and fetch functions. ### Signature - `defineQueryOptions(setupOptions: (params?) => DefineQueryOptions)` (Dynamic) - `defineQueryOptions(options: DefineQueryOptions)` (Static) ### Parameters - **setupOrOptions** (Function | Object) - Required - The query options object or a function that returns the query options. ### Returns - **Function | Object** - Returns a tagged query options object or a factory function that produces one. ### Example ```ts import { defineQueryOptions } from '@pinia/colada' const documentDetailsQuery = defineQueryOptions((id: number ) => ({ key: ['documents', id], query: () => fetchDocument(id), })) queryCache.getQueryData(documentDetailsQuery(4).key) ``` ``` -------------------------------- ### Configure Custom Storage Source: https://pinia-colada.esm.dev/cookbook/cache-persistence.html Implement custom storage backends like IndexedDB and ensure the cache is ready before mounting the application. ```typescript import { get, set } from 'idb-keyval' PiniaColadaCachePersister({ storage: { getItem: (key) => get(key), setItem: (key, value) => set(key, value), }, }) ``` ```typescript import { PiniaColadaCachePersister, isCacheReady } from '@pinia/colada-plugin-cache-persister' async function main() { const app = createApp(App) app.use(pinia) app.use(PiniaColada, { plugins: [PiniaColadaCachePersister()], }) await isCacheReady() app.mount('#app') } main() ``` -------------------------------- ### Implement custom loading utilities Source: https://pinia-colada.esm.dev/cookbook/migration-tvq.html Create custom composables like useIsLoading and useIsMutating by accessing the query or mutation cache directly. ```typescript import { useMutationCache , useQueryCache , type UseMutationEntryFilter , type UseQueryEntryFilter , } from '@pinia/colada' import { computed , type ComputedRef } from 'vue' /** * Returns a computed ref that indicates whether there are any ongoing queries * matching the provided filters. * @param filters - Optional filters to narrow down the queries to check. * @returns A computed ref that is true if there are ongoing queries, false otherwise. */ export function useIsLoading ( filters ?: UseQueryEntryFilter ): ComputedRef { const queryCache = useQueryCache () return computed (() => queryCache . getEntries ( filters ). some (( entry ) => entry . asyncStatus . value === 'loading'), ) } /** * Returns a computed ref that indicates whether there are any ongoing mutations * matching the provided filters. * * @param filters - Optional filters to narrow down the mutations to check. * @returns A computed ref that is true if there are ongoing mutations, false otherwise. */ export function useIsMutating ( filters ?: UseMutationEntryFilter ): ComputedRef { const mutationCache = useMutationCache () return computed (() => mutationCache . getEntries ( filters ). some (( entry ) => entry . asyncStatus . value === 'loading'), ) } ``` -------------------------------- ### Basic Mutation Implementation Source: https://pinia-colada.esm.dev/quick-start.html Demonstrates creating a mutation using useMutation, which requires manual invocation via the mutate function. ```vue ``` -------------------------------- ### useMutation(options) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/useMutation.html Sets up a mutation with specified options and returns a mutation object containing methods and state. ```APIDOC ## useMutation(options) ### Description Sets up a mutation. This function is used to perform side effects or data modifications. ### Parameters - **options** (UseMutationOptions) - Required - Options to configure the mutation behavior. ### Returns - **UseMutationReturn** - An object containing the mutation state and the `mutate` function. ### Example ```ts const queryCache = useQueryCache() const { mutate, status, error } = useMutation({ mutation: (id: number) => fetch(`/api/todos/${id}`), onSuccess() { queryCache.invalidateQueries('todos') }, }) ``` ``` -------------------------------- ### PiniaColadaDelay(options?) Source: https://pinia-colada.esm.dev/api/plugins/delay/src/functions/PiniaColadaDelay.html Initializes the delay plugin to manage async status transitions for queries and mutations. ```APIDOC ## PiniaColadaDelay(options?) ### Description Delays the `asyncStatus` of both queries and mutations by a specified amount of time to avoid flickering. Options apply to both, with optional `query` and `mutations` nested overrides. ### Signature `function PiniaColadaDelay(options?): PiniaColadaPlugin;` ### Parameters - **options** (PiniaColadaDelayOptions) - Optional - Plugin configuration options for controlling delay behavior. ### Returns - **PiniaColadaPlugin** - Returns a plugin instance for Pinia Colada. ``` -------------------------------- ### Define dynamic query options Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineQueryOptions.html Demonstrates creating a dynamic query configuration that accepts parameters and provides type-safe access to query keys. ```typescript import { defineQueryOptions } from '@pinia/colada' const documentDetailsQuery = defineQueryOptions((id: number ) => ({ key: ['documents', id], query: () => fetchDocument(id), })) queryCache.getQueryData(documentDetailsQuery(4).key) // typed ``` -------------------------------- ### Configure placeholderData property Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineInfiniteQueryOptionsTagged.html Provides initial data to display while the query is loading, without affecting the cache state. ```typescript optional placeholderData?: | NoInfer | NoInfer> | ((...args) => | NoInfer | NoInfer> | undefined); ``` ```typescript DefineInfiniteQueryOptions.placeholderData ``` -------------------------------- ### PiniaColadaDelayQuery(options?) Source: https://pinia-colada.esm.dev/api/plugins/delay/src/functions/PiniaColadaDelayQuery.html Initializes the delay plugin for Pinia Colada queries. ```APIDOC ## Function: PiniaColadaDelayQuery(options?) ### Description Delays the `asyncStatus` of queries by a certain amount of time to avoid flickering between refreshes. ### Signature `function PiniaColadaDelayQuery(options?): PiniaColadaPlugin;` ### Parameters - **options** (Pick) - Optional - Plugin options to configure the delay duration. ### Returns - **PiniaColadaPlugin** - Returns a plugin instance for Pinia Colada. ``` -------------------------------- ### Define placeholderData option Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseInfiniteQueryOptions.html Provides initial data to display while the query is loading. ```typescript optional placeholderData?: | NoInfer | NoInfer> | ((...args) => | NoInfer | NoInfer> | undefined); ``` -------------------------------- ### PiniaColadaAutoRefetch(options?) Source: https://pinia-colada.esm.dev/api/plugins/auto-refetch/src/functions/PiniaColadaAutoRefetch.html Initializes the auto-refetch plugin for Pinia Colada to keep queries updated. ```APIDOC ## PiniaColadaAutoRefetch(options?) ### Description Plugin that automatically refreshes queries when they become stale. ### Signature `function PiniaColadaAutoRefetch(options?): PiniaColadaPlugin;` ### Parameters - **options** (PiniaColadaAutoRefetchOptions) - Optional - Configuration options for the plugin. Defaults to `{}`. ### Returns - **PiniaColadaPlugin** - The configured plugin instance. ``` -------------------------------- ### useInfiniteQuery Source: https://pinia-colada.esm.dev/api/%40pinia/colada Stores and merges paginated data into a single cache entry for infinite scrolling. ```APIDOC ## useInfiniteQuery ### Description Store and merge paginated data into a single cache entry. Allows to handle infinite scrolling. ### Usage `useInfiniteQuery(options)` ``` -------------------------------- ### onSettled Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineMutationOptionsTagged.html A callback that runs after the mutation is settled, regardless of whether it succeeded or failed. ```APIDOC ## onSettled ### Description Runs after the mutation is settled, regardless of the result. ### Parameters - **data** (NoInfer | undefined) - The result of the mutation. undefined if the mutation failed. - **error** (TError | undefined) - The error thrown by the mutation. undefined if the mutation was successful. - **vars** (NoInfer) - The variables passed to the mutation. - **context** (UseMutationContextCommon & UseMutationGlobalContext) - The merged context from onMutate and the global context. ``` -------------------------------- ### UseQueryOptions Configuration Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseQueryOptions.html Configuration options for controlling query behavior, including placeholder data, refetching triggers, and stale time settings. ```APIDOC ## UseQueryOptions ### Description Configuration options for the useQuery hook to manage data fetching, caching, and lifecycle events. ### Properties - **placeholderData** (NoInfer | NoInfer | Function) - Optional - Data shown while the query is loading. Does not persist to cache. - **refetchOnMount** (MaybeRefOrGetter) - Optional - Whether to refetch on component mount. Default: true. - **refetchOnReconnect** (MaybeRefOrGetter) - Optional - Whether to refetch when network reconnects. Default: true. - **refetchOnWindowFocus** (MaybeRefOrGetter) - Optional - Whether to refetch when window regains focus. Default: true. - **retry** (number | RetryOptions | Function) - Optional - Retry logic configuration for failed queries. - **ssrCatchError** (boolean) - Optional - Whether to catch errors during SSR. Default: false. - **staleTime** (number) - Optional - Time in ms before data is considered stale. Default: 5000. ``` -------------------------------- ### useQuery(options) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/useQuery.html Ensures and returns a shared query state based on the key option. ```APIDOC ## useQuery(options) ### Description Ensures and returns a shared query state based on the `key` option. ### Signature `function useQuery(options): UseQueryReturn` ### Parameters - **options** (`UseQueryOptions` | `() => DefineQueryOptions`) - Required - The options of the query. ### Returns - `UseQueryReturn` ### Example ```ts const { state } = useQuery({ key: ['documents'], query: () => getDocuments(), }) ``` ``` -------------------------------- ### PiniaColadaRetry(globalOptions?) Source: https://pinia-colada.esm.dev/api/plugins/retry/src/functions/PiniaColadaRetry.html Initializes the retry plugin for Pinia Colada, allowing failed queries to be retried based on provided global options. ```APIDOC ## PiniaColadaRetry(globalOptions?) ### Description Plugin that adds the ability to retry failed queries. ### Signature `function PiniaColadaRetry(globalOptions?): (context) => void;` ### Parameters - **globalOptions** (RetryOptions) - Optional - Global options for the retries. ### Returns - **(context) => void** - A function that accepts a context object. ``` -------------------------------- ### useInfiniteQuery(getter) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/useInfiniteQuery.html Initializes an infinite query using a getter function that returns defined infinite query options. ```APIDOC ## useInfiniteQuery(getter) ### Description Stores and merges paginated data into a single cache entry using a getter function that returns options defined with defineInfiniteQueryOptions. ### Parameters - **options** (() => DefineInfiniteQueryOptions) - Required - A getter function that returns the infinite query configuration. ### Returns - **UseInfiniteQueryReturn** - An object containing the state and methods to manage the infinite query. ``` -------------------------------- ### useQuery Source: https://pinia-colada.esm.dev/api/%40pinia/colada Ensures and returns a shared query state based on the provided key option. ```APIDOC ## useQuery ### Description Ensures and returns a shared query state based on the `key` option. This is the primary way to fetch and manage query state in components. ### Usage `useQuery(options)` ``` -------------------------------- ### Migrate useQuery and useQueryState (0.21 to 1.0) Source: https://pinia-colada.esm.dev/cookbook/migrations.html Updates usage to remove the two-parameter form in favor of a single function parameter. ```ts useQuery(useContactList, () => ({ search: search.value })) useQueryState(useContactList, () => ({ search: search.value })) ``` ```ts useQuery(() => useContactList({ search: search.value })) useQueryState(() => useContactList({ search: search.value }).key) ``` -------------------------------- ### PiniaColadaDelayMutations(options?) Source: https://pinia-colada.esm.dev/api/plugins/delay/src/functions/PiniaColadaDelayMutations.html Initializes the delay plugin for Pinia Colada mutations. ```APIDOC ## PiniaColadaDelayMutations(options?) ### Description Delays the `asyncStatus` of mutations by a certain amount of time to avoid flickering. ### Signature `function PiniaColadaDelayMutations(options?): PiniaColadaPlugin;` ### Parameters - **options** (Pick) - Optional - Plugin options to configure the delay duration. ``` -------------------------------- ### useMutation Source: https://pinia-colada.esm.dev/api/%40pinia/colada Sets up a mutation for performing data updates. ```APIDOC ## useMutation ### Description Sets up a mutation. Used to perform side effects or data modifications. ### Usage `useMutation(options)` ``` -------------------------------- ### Define initialData option Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseInfiniteQueryOptions.html Provides initial data for the query, setting the state to success immediately. ```typescript optional initialData?: () => TDataInitial; ``` -------------------------------- ### PiniaColadaAutoRefetchOptions Source: https://pinia-colada.esm.dev/api/plugins/auto-refetch/src/interfaces/PiniaColadaAutoRefetchOptions.html Configuration interface for enabling and customizing auto-refetch behavior. ```APIDOC ## Interface: PiniaColadaAutoRefetchOptions ### Description Options for the auto-refetch plugin. ### Properties - **autoRefetch** (number | boolean | (state) => number | boolean) - Optional - Whether to enable auto refresh by default. Defaults to `false`. ``` -------------------------------- ### Refactoring with defineQueryOptions Source: https://pinia-colada.esm.dev/quick-start.html Combines key factories and defineQueryOptions to create reusable, type-safe query definitions. ```ts import { getProductById } from '@/api/products' import { defineQueryOptions } from '@pinia/colada' export const PRODUCT_QUERY_KEYS = { root: ['products'] as const, byId: (id: string) => [...PRODUCT_QUERY_KEYS.root, id] as const, } ``` -------------------------------- ### Options property Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseQueryEntry.html Configuration options used to create the query. ```typescript options: | UseQueryOptionsWithDefaults | null; ``` -------------------------------- ### UseInfiniteQueryFnContext Interface Properties Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseInfiniteQueryFnContext.html Definitions for the entry, pageParam, and signal properties within the context. ```typescript entry: UseQueryEntry; ``` ```typescript pageParam: TPageParam; ``` ```typescript signal: AbortSignal; ``` -------------------------------- ### Migrate PiniaColada plugin options (0.13 to 0.14) Source: https://pinia-colada.esm.dev/cookbook/migrations.html Updates plugin configuration to move global options under the queryOptions key and ensures empty objects are passed when no options are provided. ```ts app.use(PiniaColada, { staleTime: 10_000, refetchOnWindowFocus: true, plugins: [/* ... */], }) app.use(PiniaColada) ``` ```ts app.use(PiniaColada, { queryOptions: { staleTime: 10_000, refetchOnWindowFocus: true, }, plugins: [/* ... */], }) app.use(PiniaColada, {}) ``` -------------------------------- ### Configure refetchOnMount property Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineInfiniteQueryOptionsTagged.html Determines if the query should refetch when the component mounts. ```typescript optional refetchOnMount?: RefetchOnControl; ``` ```typescript true ``` -------------------------------- ### Enable production devtools Source: https://pinia-colada.esm.dev/guide/installation.html Use the production-specific component to keep devtools enabled in production builds. ```template ``` -------------------------------- ### loadNextPage Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseInfiniteQueryReturn.html Loads the next page of data for the infinite query. ```APIDOC ## loadNextPage(options?) ### Description Loads the next page of data. ### Parameters - **options** (UseInfiniteQueryLoadMoreOptions) - Optional - Configuration options for loading more data. ### Returns - **Promise** - A promise that resolves when the next page has been loaded. ``` -------------------------------- ### loadPreviousPage Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseInfiniteQueryReturn.html Loads the previous page of data for the infinite query. ```APIDOC ## loadPreviousPage(options?) ### Description Load the previous page of data. Requires UseInfiniteQueryOptions.getPreviousPageParam to be defined. ### Parameters - **options** (UseInfiniteQueryLoadMoreOptions) - Optional - Configuration options for loading more data. ### Returns - **Promise** - A promise that resolves when the previous page has been loaded. ``` -------------------------------- ### Define query key Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineQueryOptionsTagged.html Defines the key property and demonstrates usage with reactive dependencies. ```typescript key: EntryKeyTagged; ``` ```typescript import { useRoute } from 'vue-router' import { useQuery } from '@pinia/colada' const route = useRoute() const { data } = useQuery({ // pass a getter function (or computed, ref, etc.) to ensure reactivity key: () => ['user', route.params.id], query: () => fetchUser(route.params.id), }) ``` ```typescript DefineQueryOptions.key ``` -------------------------------- ### Define reusable query options Source: https://pinia-colada.esm.dev/cookbook/migration-tvq.html Use defineQueryOptions to create reusable query configurations, which is the preferred approach in Pinia Colada. ```typescript export const todosQuery = queryOptions({ queryKey: ['todos'], queryFn: getList, }) export const todosQuery = defineQueryOptions({ key: ['list'], query: getList, }) ``` -------------------------------- ### refetch Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseInfiniteQueryReturn.html Triggers a new fetch for the query, ignoring existing fresh data. ```APIDOC ## refetch(throwOnError?) ### Description Ignores fresh data and triggers a new fetch. ### Parameters - **throwOnError** (boolean) - Optional - Whether to throw an error if the fetch fails. Defaults to false. ### Returns - **Promise** - A promise that resolves when the fetch is done. ``` -------------------------------- ### defineMutationOptions(options) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineMutationOptions.html Defines static mutation options that can be passed directly to useMutation. ```APIDOC ## defineMutationOptions(options) ### Description Defines static mutation options that can be passed directly to useMutation. ### Parameters - **options** (UseMutationOptions) - Required - The mutation options object. ### Returns - **DefineMutationOptionsTagged** - A tagged object containing the mutation configuration. ``` -------------------------------- ### defineInfiniteQueryOptions(options) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineInfiniteQueryOptions.html Defines static infinite query options that are type-safe and can be passed directly to useInfiniteQuery or used with queryCache.getQueryData(). ```APIDOC ## defineInfiniteQueryOptions(options) ### Description Defines static infinite query options that are type-safe. This is useful for standard queries where the configuration does not change dynamically. ### Parameters - **options** (UseInfiniteQueryOptions) - Required - The infinite query configuration object containing key, query, initialPageParam, and getNextPageParam. ### Returns - **DefineInfiniteQueryOptionsTagged** - A tagged object containing the query configuration. ### Example ```ts import { defineInfiniteQueryOptions } from '@pinia/colada' const itemsQuery = defineInfiniteQueryOptions({ key: ['items'], query: ({ pageParam }) => fetchItems(pageParam), initialPageParam: 0, getNextPageParam: (lastPage) => lastPage.nextCursor, }) ``` ``` -------------------------------- ### Define initialData property Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineInfiniteQueryOptionsTagged.html Defines the initial data configuration option. ```typescript optional initialData?: () => TDataInitial; ``` ```typescript DefineInfiniteQueryOptions.initialData ``` -------------------------------- ### Integrate Devtools component Source: https://pinia-colada.esm.dev/guide/installation.html Include the devtools component in the root App.vue file. ```vue ``` -------------------------------- ### Define Reusable Query Options Source: https://pinia-colada.esm.dev/quick-start.html Creates a reusable query configuration using defineQueryOptions, which centralizes fetching logic and key generation. ```typescript export const productDetailsQuery = defineQueryOptions (( id : string) => ({ key : PRODUCT_QUERY_KEYS . byId ( id ), query : () => getProductById ( id ), })) ``` -------------------------------- ### useQueryState(key) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/useQueryState.html Provides reactive access to the state of a query entry identified by the provided key. ```APIDOC ## useQueryState(key) ### Description Provides reactive access to the state of a query entry without fetching it. ### Parameters - **key** (MaybeRefOrGetter> | MaybeRefOrGetter) - Required - The tagged key or key of the query entry to access. ### Returns - **UseQueryStateReturn** - An object containing the reactive state of the query entry. ### Type Parameters - **TData** - The type of the data. - **TError** - The type of the error (default: { custom: Error }). - **TDataInitial** - The type of the initial data (default: undefined). ``` -------------------------------- ### Configure meta information Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/UseQueryOptions.html Associates serializable metadata with the query, useful for SSR and custom logic. ```typescript optional meta?: MaybeRefOrGetter>; ``` ```typescript // SSR-safe: simple serializable data useQuery({ key: ['user', id], query: () => fetchUser(id), meta: { errorMessage: true } }) // Using a function to compute meta useQuery({ key: ['user', id], query: () => fetchUser(id), meta: () => ({ timestamp: Date.now() }) }) // Skipping meta during SSR useQuery({ key: ['user', id], query: () => fetchUser(id), meta: { onError: import.meta.env.SSR ? undefined : ((err) => console.log('error')) } }) ``` -------------------------------- ### Define initialPageParam property Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineInfiniteQueryOptionsTagged.html Defines the initial page parameter configuration option. ```typescript initialPageParam: _IsMaybeRefOrGetter TPageParam)>> extends true ? | _UnwrapMaybeRefOrGetter | _UnwrapMaybeRefOrGetter<() => TPageParam> : TPageParam | (() => TPageParam); ``` -------------------------------- ### PiniaColadaQueryHooksPluginOptions Interface Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/PiniaColadaQueryHooksPluginOptions.html Configuration options for defining global query lifecycle hooks. ```APIDOC ## Interface: PiniaColadaQueryHooksPluginOptions ### Properties #### onError? (optional) - **Type**: (error: TError, entry: UseQueryEntry) => unknown - **Description**: Global error handler for all queries. #### onSettled? (optional) - **Type**: (data: TData | undefined, error: TError | null, entry: UseQueryEntry) => unknown - **Description**: Global handler for when a query is settled (either successfully or with an error). Will await for the onSuccess or onError handlers to resolve if they return a promise. #### onSuccess? (optional) - **Type**: (data: TData, entry: UseQueryEntry) => unknown - **Description**: Global handler for when a query is successful. ``` -------------------------------- ### Define ENTRY_DATA_INITIAL_TAG Source: https://pinia-colada.esm.dev/api/%40pinia/colada/type-aliases/EntryKeyTagged.html Tag for the initial data type. ```typescript [ENTRY_DATA_INITIAL_TAG]: TDataInitial; ``` -------------------------------- ### Access and Update Query Cache Source: https://pinia-colada.esm.dev/quick-start.html Demonstrates type-safe retrieval and manual updates of cached query data using the useQueryCache composable. ```typescript import { useQueryCache } from '@pinia/colada' import { productDetailsQuery } from '@/queries/products' const queryCache = useQueryCache () // Typed and type-safe access to cached data 💯 const cachedProduct = queryCache . getQueryData ( productDetailsQuery ('24'). key ) /* * Setting data is also type-safe */ queryCache . setQueryData ( productDetailsQuery ('24'). key , { id : '24', name : 'New Product Name', color : 'red', // oops... imagesrc: '...', Object literal may only specify known properties, and 'imagesrc' does not exist in type 'NoInfer | ((oldData: ProductT | undefined) => ProductT)'. imageAlt : '...', price : 65, availability : 5, rating : 4.5, description : '...', }) ``` -------------------------------- ### Define enabled property Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineInfiniteQueryOptionsTagged.html Defines the enabled configuration option. ```typescript optional enabled?: boolean; ``` -------------------------------- ### useMutationCache Source: https://pinia-colada.esm.dev/api/%40pinia/colada/variables/useMutationCache.html A Pinia store definition providing methods to interact with mutation entries. ```APIDOC ## useMutationCache ### Description Provides access to the mutation cache store. It can be used within setup functions, other composables, or injectable contexts. ### Methods - **create(options, key?, vars?)**: Creates a new mutation entry. - **get(id)**: Retrieves a mutation entry by its ID. - **getEntries(filters)**: Returns a list of mutation entries based on provided filters. - **mutate(entry)**: Executes a mutation entry and returns a promise with the result. - **remove(entry)**: Removes a mutation entry from the cache. - **ensure(entry, vars)**: Ensures a mutation entry exists with the specified variables. - **ensureDefinedMutation(fn)**: Ensures a defined mutation entry exists. - **extend(_entry)**: Extends an existing mutation entry. - **setEntryState(entry, state)**: Updates the state of a mutation entry. - **untrack(entry)**: Stops tracking a mutation entry. ``` -------------------------------- ### defineQuery(options) Source: https://pinia-colada.esm.dev/api/%40pinia/colada/functions/defineQuery.html Defines a query with static options, allowing for the reuse of query state across multiple components. ```APIDOC ## defineQuery(options) ### Description Defines 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 allows static values in options. ### Parameters - **options** (DefineQueryOptions) - Required - The options to define the query. ### Returns - **Function** - A function that returns UseQueryReturn. ### Example ```ts const useTodoList = defineQuery({ key: ['todos'], query: () => fetch('/api/todos', { method: 'GET' }), }) ``` ``` -------------------------------- ### onSuccess Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineMutationOptionsTagged.html A callback that runs only when the mutation completes successfully. ```APIDOC ## onSuccess ### Description Runs if the mutation is successful. ### Parameters - **data** (NoInfer) - The result of the mutation. - **vars** (NoInfer) - The variables passed to the mutation. - **context** (UseMutationContextCommon & UseMutationGlobalContext) - The merged context from onMutate and the global context. ``` -------------------------------- ### Prefetching with defineQueryOptions Source: https://pinia-colada.esm.dev/cookbook/prefetching.html Use ensure and refresh on a query defined with defineQueryOptions to prefetch data. This approach is type-safe and allows components to reuse cached data or ongoing requests. ```typescript import { defineQueryOptions, useQueryCache } from '@pinia/colada' const userListQuery = defineQueryOptions({ key: ['users', 'list'], query: () => fetch('/api/users').then((res) => res.json()), }) const queryCache = useQueryCache() await queryCache.refresh(queryCache.ensure(userListQuery)) ``` -------------------------------- ### Configure refetchOnWindowFocus property Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineInfiniteQueryOptionsTagged.html Determines if the query should refetch when the window regains focus. ```typescript optional refetchOnWindowFocus?: RefetchOnControl; ``` ```typescript true ``` -------------------------------- ### Define meta option Source: https://pinia-colada.esm.dev/api/%40pinia/colada/interfaces/DefineMutationOptionsTagged.html Defines metadata associated with the mutation. ```typescript optional meta?: Record; ```