Loading...
Loading...
Pinia Colada expert for Vue 3 — queries, mutations, keys, invalidation, optimistic updates, pagination, and debugging.
npx skill4agent add pilag6/skills-claude-code pinia-coladastatusasyncStatusstatus'pending' | 'success' | 'error'asyncStatus'loading' | 'idle'status === 'pending'asyncStatus === 'loading' && status === 'success'refresh()refetch()refresh()staleTimerefetch()query()export const productKeys = {
root: () => ['products'] as const,
list: (params: { q?: string; page?: number }) => ['products', 'list', params] as const,
detail: (id: string) => ['products', 'detail', id] as const,
}as constkey: () => productKeys.detail(id.value)query()useQuery()const productQuery = useQuery(() => ({
key: productKeys.detail(route.params.id as string),
enabled: !!route.params.id,
query: () => productService.getById(route.params.id as string),
}))defineQueryOptions()export const productDetailQuery = defineQueryOptions((id: string) => ({
key: productKeys.detail(id),
query: () => productService.getById(id),
}))
// Usage
const q = useQuery(() => ({ ...productDetailQuery(id.value), enabled: !!id.value }))defineQuery()const queryCache = useQueryCache()
const updateProduct = useMutation(() => ({
mutation: (vars: { id: string; name: string }) => productService.update(vars),
onSuccess: async (data, vars) => {
await queryCache.invalidateQueries({ key: productKeys.detail(vars.id) })
await queryCache.invalidateQueries({ key: productKeys.root() })
},
}))invalidateQueries| Action | Invalidate |
|---|---|
| Create | |
| Update | |
| Delete | Lists, optionally remove detail |
const page = ref(1)
const listQuery = useQuery(() => ({
key: productKeys.list({ q: search.value, page: page.value }),
query: () => productService.list({ q: search.value, page: page.value }),
placeholderData: (prev) => prev, // Keep previous page visible
}))mutation.variablesconst mutate = useMutation(() => ({
onMutate: async (vars) => {
const key = productKeys.detail(vars.id)
await queryCache.cancelQueries({ key })
const oldValue = queryCache.getQueryData(key)
const newValue = oldValue ? { ...oldValue, ...vars } : oldValue
queryCache.setQueryData(key, newValue)
return { key, oldValue, newValue }
},
mutation: (vars) => productService.update(vars),
onError: (err, vars, ctx) => {
if (!ctx) return
// Race-safe rollback
if (queryCache.getQueryData(ctx.key) === ctx.newValue) {
queryCache.setQueryData(ctx.key, ctx.oldValue)
}
},
onSettled: async (data, err, vars, ctx) => {
if (ctx) await queryCache.invalidateQueries({ key: ctx.key })
},
}))useQueryCache()| Problem | Solution |
|---|---|
| Query doesn't refetch when X changes | Include X in the key, use |
| Invalidation doesn't work | Check key hierarchy, use exact matching or predicate |
| Old data while loading | Expected behavior — |
| Optimistic rollback bugs | Cancel queries before cache write, use race-safe rollback |
useQuerydefineQueryOptionsuseMutationstatusasyncStatus