К основному содержанию
скилл CX Codex

pinia-colada — скилл для Claude Code: кеширование запросов Vue/Nuxt

Скилл pinia-colada для управления асинхронным состоянием в Vue и Nuxt через useQuery и useMutation. Помогает при кешировании, SSR, инвалидации кеша и миграции с TanStack Vue Query.

MIT 253 установок ★ 250 обновлён 2026-10-20

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add secondsky/claude-skills --skill pinia-colada -a claude-code
Открыть на GitHub

Что делает pinia-colada

pinia-colada — это скилл, который интегрирует библиотеку данных Pinia Colada в ваш AI-редактор. Внутри скилла собраны примеры и правила для работы с useQuery (загрузка данных), useMutation (изменение данных) и useQueryCache (управление кешем). Скилл показывает, как настроить плагин в main.ts для Vue или в nuxt.config.ts для Nuxt, какие параметры передать (staleTime, gcTime, refetchOnMount), и как избежать ошибок с ключами, ошибками и гонками данных.

В скилле 12 предотвращённых ошибок: неправильные типы ключей, забытые await для mutateAsync, отсутствие инвалидации после мутаций, race condition без cancelQueries. Требует Vue 3.5.17+, Pinia 2.2.6+ или 3.0+, и для Nuxt нужно ставить @pinia/nuxt перед @pinia/colada-nuxt.

Токен-сбережение около 65% — скилл предоставляет готовые паттерны вместо написания всего с нуля. Есть 4 справочных примера: простой запрос todos, мутация с инвалидацией, оптимистичные обновления и пагинированные запросы.

Какие задачи решает

  • Настроить кеширование и refetch для асинхронного состояния в Vue 3
  • Управлять инвалидацией кеша после изменения данных на сервере
  • Реализовать SSR с гидрацией состояния и без дублирования запросов
  • Мигрировать с TanStack Vue Query на Pinia Colada без ошибок
  • Избежать race condition и гонок при одновременных запросах

Примеры запросов агенту

  • Покажи пример useQuery с ключом и обработкой ошибок для Vue 3
  • Как установить pinia-colada в Nuxt и настроить стандартные параметры кеша
  • Напиши мутацию с инвалидацией запроса todos после успеха

Как установить pinia-colada

1Через Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill pinia-colada -a claude-code

2Вручную: положить файлы

~/.claude/skills/pinia-colada/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/pinia-colada/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о pinia-colada

Как установить pinia-colada для Claude Code?

Запусти npx skills add secondsky/claude-skills --skill pinia-colada -a claude-code, затем открой файл ~/.claude/skills/pinia-colada/SKILL.md. Для других платформ замени флаг: -a codex для Codex, -a cursor для Cursor, -a gemini-cli для Gemini CLI.

Зачем нужен скилл pinia-colada?

Скилл даёт AI-помощнику знание о API Pinia Colada, правилах кеширования, типичных ошибках и готовых примерах для useQuery, useMutation и инвалидации. Без скилла редактор не подскажет, как избежать гонок данных или когда ставить await для mutateAsync.

Нужен ли мне скилл, если я уже знаю Pinia Colada?

Скилл в основном помогает AI-помощнику, но если вы сами пишете код, он может быть полезен как справочник с примерами правильного паттерна. Для чистого читателя это менее критично.

Исходный текст

SKILL.md · MIT
---
name: pinia-colada
description: "Pinia Colada data fetching for Vue/Nuxt with useQuery, useMutation. Use for async state, query cache, SSR, or encountering invalidation, hydration, TanStack Vue Query migration errors."
license: MIT
metadata:
  version: "2.0.0"
  pinia_colada_version: "0.17.9"
  pinia_version: "3.0.4"
  vue_version: "3.5.25"
  last_verified: "2025-11-28"
  production_tested: true
  token_savings: "~65%"
  errors_prevented: 12
  references_included: 4
  keywords:
    - Pinia Colada
    - "@pinia/colada"
    - useQuery
    - useMutation
    - useQueryCache
    - data fetching
    - async state
    - Vue 3
    - Nuxt
    - Pinia
    - server state
    - caching
    - staleTime
    - gcTime
    - query invalidation
    - prefetching
    - optimistic updates
    - mutations
    - query keys
    - paginated queries
    - SSR
    - server-side rendering
    - Nuxt module
    - "@pinia/colada-nuxt"
    - query cache
    - auto-refetch
    - cache invalidation
    - request deduplication
    - loading states
    - error handling
    - onSettled
    - onSuccess
    - onError
    - defineColadaLoader
---
# Pinia Colada - Smart Data Fetching for Vue

**Status**: Production Ready ✅ | **Last Updated**: 2025-11-28
**Latest Version**: @pinia/[email protected] | **Dependencies**: Vue 3.5.17+, Pinia 2.2.6+ or 3.0+

---

## Quick Start (5 Minutes)

### 1. Install Dependencies

**For Vue Projects:**
```bash
bun add @pinia/colada pinia  # preferred
# or: bun add @pinia/colada pinia
```

**For Nuxt Projects:**
```bash
bun add @pinia/nuxt @pinia/colada-nuxt  # install both Pinia and Pinia Colada modules
# or: bun add @pinia/nuxt @pinia/colada-nuxt
```

**Why this matters:**
- Pinia Colada requires Pinia 2.2.6+ or 3.0+ as peer dependency
- Nuxt module handles SSR serialization automatically
- Vue 3.5.17+ required for optimal reactivity

### 2. Set Up Pinia Colada Plugin

**For Vue Projects:**
```typescript
// src/main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { PiniaColada } from '@pinia/colada'
import App from './App.vue'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(PiniaColada, {
  // Optional: Configure defaults
  query: {
    staleTime: 5000,        // 5 seconds
    gcTime: 5 * 60 * 1000,  // 5 minutes (garbage collection)
    refetchOnMount: true,
    refetchOnWindowFocus: false,
  },
})

app.mount('#app')
```

**For Nuxt Projects:**
```typescript
// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    '@pinia/nuxt',           // Must be before @pinia/colada-nuxt
    '@pinia/colada-nuxt',
  ],

  // Optional: Configure Pinia Colada
  piniaColada: {
    query: {
      staleTime: 5000,
      gcTime: 5 * 60 * 1000,
    },
  },
})
```

**CRITICAL:**
- For Nuxt: `@pinia/nuxt` must be listed before `@pinia/colada-nuxt`
- Plugin must be registered after Pinia instance
- Configuration is optional - sensible defaults provided

### 3. Create First Query

```vue
<script setup lang="ts">
import { useQuery } from '@pinia/colada'

interface Todo {
  id: number
  title: string
  completed: boolean
}

async function fetchTodos(): Promise<Todo[]> {
  const response = await fetch('/api/todos')
  if (!response.ok) {
    throw new Error('Failed to fetch todos')
  }
  return response.json()
}

const {
  data,       // Ref<Todo[] | undefined>
  isPending,  // Ref<boolean> - initial loading
  isLoading,  // Ref<boolean> - any loading (including refetch)
  error,      // Ref<Error | null>
  refresh,    // () => Promise<void> - manual refetch
} = useQuery({
  key: ['todos'],
  query: fetchTodos,
})
</script>

<template>
  <div>
    <div v-if="isPending">Loading todos...</div>
    <div v-else-if="error">Error: {{ error.message }}</div>
    <ul v-else-if="data">
      <li v-for="todo in data" :key="todo.id">
        {{ todo.title }}
      </li>
    </ul>
  </div>
</template>
```

**CRITICAL:**
- Query `key` must be an array (or getter returning array) for consistent caching
- Query `query` is the async function that fetches data
- Throw errors in query function for proper error handling
- `isPending` is `true` only on initial load, `isLoading` includes refetches

### 4. Create First Mutation

```vue
<script setup lang="ts">
import { useMutation, useQueryCache } from '@pinia/colada'

interface NewTodo {
  title: string
}

async function createTodo(newTodo: NewTodo) {
  const response = await fetch('/api/todos', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(newTodo),
  })
  if (!response.ok) throw new Error('Failed to create todo')
  return response.json()
}

const queryCache = useQueryCache()

const {
  mutate,        // (variables: NewTodo) => Promise<void>
  mutateAsync,   // (variables: NewTodo) => Promise<Result>
  isPending,     // Ref<boolean>
  error,         // Ref<Error | null>
  data,          // Ref<Result | undefined>
} = useMutation({
  mutation: createTodo,

  // Invalidate todos query after mutation succeeds
  async onSettled({ id }) {
    await queryCache.invalidateQueries({ key: ['todos'] })
  },
})

function handleAddTodo(title: string) {
  mutate({ title })
}
</script>

<template>
  <form @submit.prevent="handleAddTodo(newTitle)">
    <input v-model="newTitle" required />
    <button type="submit" :disabled="isPending">
      {{ isPending ? 'Adding...' : 'Add Todo' }}
    </button>
    <div v-if="error">Error: {{ error.message }}</div>
  </form>
</template>
```

**Why this works:**
- `onSettled` runs after success or error, perfect for invalidation
- `invalidateQueries` marks matching queries as stale and refetches active ones
- `mutate` is fire-and-forget, `mutateAsync` returns Promise for await
- Mutations don't cache by default (correct behavior for writes)

---

## Critical Rules

### Always Do

✅ Include all variables used in query function in the key
✅ Throw errors in query/mutation functions for proper error handling
✅ Use `useQueryCache()` for invalidation in mutations
✅ Use `isPending` for initial load, `isLoading` for any loading state
✅ Await `invalidateQueries()` in `onSettled` when you need data fresh before continuing
✅ Use `placeholderData` for paginated queries to avoid flashing
✅ Snapshot cache with `getQueryData` before optimistic updates
✅ Return context from `onMutate` for rollback in `onError`
✅ Configure `staleTime` and `gcTime` at plugin level for app-wide defaults
✅ Use reusable composables for queries instead of inline useQuery

### Never Do

❌ Never use plain strings as keys - always use arrays
❌ Never return undefined from query function - throw errors instead
❌ Never mutate `data.value` directly - it's readonly
❌ Never forget to invalidate related queries after mutations
❌ Never use `onSuccess` in queries (not available, use watch instead)
❌ Never forget to await `mutateAsync()` - it returns a Promise
❌ Never skip `cancelQueries` before optimistic updates (causes race conditions)
❌ Never use `getQueryData` without checking for undefined
❌ Never invalidate queries in `onMutate` (do it in `onSettled`)
❌ Never hardcode URLs - use environment variables for API base URLs

---

## Top 5 Errors Prevention

This skill prevents **12 documented errors**. Here are the top 5:

### Error #1: Query Not Refetching After Mutation
**Error**: Data doesn't update in UI after successful mutation
**Prevention**: Always use `invalidateQueries` in `onSettled`:
```typescript
useMutation({
  mutation: createTodo,
  async onSettled() {
    await queryCache.invalidateQueries({ key: ['todos'] })
  },
})
```
**See**: `references/error-catalog.md` #1

### Error #2: Race Condition with Optimistic Updates
**Error**: Optimistic update gets overwritten by in-flight request
**Prevention**: Always call `cancelQueries` in `onMutate`:
```typescript
onMutate(id) {
  cache.cancelQueries({ key: ['todos'] })
  // Then do optimistic update
}
```
**See**: `references/error-catalog.md` #2

### Error #3: SSR Hydration Mismatch
**Error**: `Hydration completed but contains mismatches`
**Prevention**: Set `refetchOnMount: false` for SSR queries
```typescript
useQuery({
  key: ['todos'],
  query: fetchTodos,
  refetchOnMount: false, // Prevents SSR hydration mismatch
})
```
**See**: `references/error-catalog.md` #3

### Error #4: Query Key Not Reactive
**Error**: Query doesn't refetch when variable changes
**Prevention**: Use function for reactive keys:
```typescript
// ❌ Wrong - static key
key: ['todos', id.value]

// ✅ Correct - reactive key
key: () => ['todos', id.value]
```
**See**: `references/error-catalog.md` #4

### Error #5: Nuxt Module Order Wrong
**Error**: `PiniaColada plugin not found` or SSR errors
**Prevention**: Always put `@pinia/nuxt` first:
```typescript
export default defineNuxtConfig({
  modules: [
    '@pinia/nuxt',           // MUST be first
    '@pinia/colada-nuxt',    // Then Colada
  ],
})
```
**See**: `references/error-catalog.md` #10

**For complete error catalog** (all 12 errors): See `references/error-catalog.md`

---

## Using Bundled Resources

### References (references/)

Detailed guides loaded when needed:

- **`references/setup-guide.md`** - Complete 8-step setup process
  - Install and configure plugin
  - Create reusable query composables
  - Understanding query keys
  - Implementing mutations
  - Optimistic updates
  - Query invalidation strategies
  - Paginated queries
  - SSR and Nuxt integration
  - **Load when**: User needs detailed setup instructions or advanced patterns

- **`references/common-patterns.md`** - 12 common patterns
  - Dependent queries
  - Parallel queries
  - Conditional queries
  - Background sync pattern
  - Prefetching on hover
  - Mutation with multiple invalidations
  - Infinite queries
  - Optimistic deletion
  - Query with retry logic
  - Query with polling
  - Query cache seeding
  - Manual query triggering
  - **Load when**: User asks "how do I..." or needs specific pattern

- **`references/error-catalog.md`** - All 12 documented errors
  - Complete error messages and solutions
  - Prevention strategies
  - Official sources cited
  - Prevention checklist
  - **Load when**: User encounters error or wants to prevent issues

- **`references/configuration.md`** - Full configuration reference
  - Plugin options (Vue and Nuxt)
  - Per-query options
  - Mutation options
  - Query cache methods
  - Advanced patterns (env-specific, error handling, devtools)
  - TypeScript configuration
  - Performance optimization
  - **Load when**: User needs configuration details or advanced setup

- **`references/migration-from-tanstack-vue-query.md`** - Migration guide
  - API differences
  - Codemod suggestions
  - Breaking changes
  - **Load when**: User mentions TanStack Vue Query or migration

---

## Common Use Cases

1. **Basic Todo List with CRUD** - Query + mutation with invalidation (10 min) → See `references/setup-guide.md` Steps 2-4
2. **Paginated Data Table** - Reactive keys with placeholderData (15 min) → See `references/setup-guide.md` Step 7
3. **Optimistic UI Updates** - Mutation with onMutate/onError rollback (20 min) → See `references/setup-guide.md` Step 5
4. **Nuxt SSR Application** - Auto-imports with refetchOnMount config (15 min) → See `references/setup-guide.md` Step 8
5. **Real-time Dashboard** - Background polling with refetchInterval (10 min) → See `references/common-patterns.md` Pattern 4

**For complete code examples** of all 5 use cases, see `references/setup-guide.md` and `references/common-patterns.md`.

---

## When to Load Detailed References

**Load `references/setup-guide.md` when:**
- User needs complete 8-step setup process
- User asks about query keys or reactive keys
- User needs optimistic updates implementation
- User asks about SSR/Nuxt setup
- User needs pagination implementation

**Load `references/common-patterns.md` when:**
- User asks "how do I..." followed by specific pattern
- User needs dependent queries
- User asks about prefetching
- User needs infinite scroll
- User asks about polling or background sync

**Load `references/error-catalog.md` when:**
- User encounters any error
- User asks about troubleshooting
- User wants to prevent known issues
- User asks "what errors should I watch out for?"
- User has SSR hydration issues

**Load `references/configuration.md` when:**
- User needs full configuration options
- User asks about plugin configuration
- User needs TypeScript types
- User wants performance optimization
- User needs custom plugins

**Load `references/migration-from-tanstack-vue-query.md` when:**
- User mentions TanStack Vue Query
- User asks about migration
- User compares Pinia Colada to TanStack Query
- User asks "what's different from..."

---

## Dependencies

**Required**:
- **@pinia/[email protected]** - Core data fetching layer
- **[email protected]+** or **[email protected]+** - State management (peer dependency)
- **[email protected]+** - Framework (peer dependency)

**Optional**:
- **@pinia/[email protected]** - Nuxt module (requires @pinia/nuxt separately)

---

## Official Documentation

- **Pinia Colada**: https://pinia-colada.esm.dev/
- **GitHub Repository**: https://github.com/posva/pinia-colada
- **Pinia**: https://pinia.vuejs.org/
- **Nuxt Module**: https://nuxt.com/modules/pinia-colada
- **Migration Guide**: https://pinia-colada.esm.dev/cookbook/migration-tvq.html

---

## Package Versions (Verified 2025-11-28)

```json
{
  "dependencies": {
    "@pinia/colada": "^0.17.9",
    "pinia": "^3.0.4",
    "vue": "^3.5.25"
  },
  "devDependencies": {
    "@pinia/colada-nuxt": "^0.17.9"
  }
}
```

**Version Notes:**
- Pinia Colada 0.17.9 is latest stable (released 2025-11-21)
- Compatible with both Pinia 2.2.6+ and 3.0+
- Requires Vue 3.5.17+ for optimal reactivity
- Nuxt module version matches core package

---

## Production Example

This skill is based on production usage in multiple Vue 3 and Nuxt applications:
- **Token Savings**: ~65% vs manual TanStack Query setup
- **Errors Prevented**: 12 common issues documented above
- **Build Time**: < 2 minutes for basic setup
- **Validation**: ✅ SSR working, ✅ TypeScript types correct, ✅ Auto-imports working in Nuxt

---

## Complete Setup Checklist

Use this checklist to verify your setup:

- [ ] Installed `@pinia/colada` and `pinia` (or `@pinia/colada-nuxt` for Nuxt)
- [ ] Registered `PiniaColada` plugin after `createPinia()` (Vue) or added to modules (Nuxt)
- [ ] Created at least one query with `useQuery`
- [ ] Created at least one mutation with `useMutation`
- [ ] Used `invalidateQueries` in mutation `onSettled` hook
- [ ] Query keys are arrays (or functions returning arrays)
- [ ] All query variables included in query key
- [ ] Errors thrown in query/mutation functions (not returned)
- [ ] Using `isPending` for initial load state
- [ ] TypeScript types defined for all data structures
- [ ] Configured `staleTime` and `gcTime` at plugin level (optional)
- [ ] Dev environment runs without errors
- [ ] SSR working if using Nuxt (check hydration)

---

**Questions? Issues?** Check: [Official docs](https://pinia-colada.esm.dev/) | `references/setup-guide.md` (8-step process) | `references/error-catalog.md` (all 12 errors) | `references/migration-from-tanstack-vue-query.md` (migration) | [GitHub](https://github.com/posva/pinia-colada/issues)

---

**This skill provides production-ready Pinia Colada setup with zero configuration errors. All 12 common issues are documented and prevented.**

© secondsky · MIT · secondsky/claude-skills

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
pinia-colada-skilld skilld-dev Скилл pinia-colada-skilld добавляет в Claude Code шаблоны и правила работы с @pinia/colada. Помогает настраивать выборку данных, мутации, сброс кэша и работу с SSR во Vue. CX Codex +1 240установок pinia Anthony Fu Загружает документацию Pinia v4.0.3 прямо в контекст агента. Агент начинает правильно определять сторы, работать с storeToRefs() и настраивать SSR-гидратацию. CX Codex +1 20 600установок vue-pinia-cursorrules-prompt-file PatrickJS Правило vue-pinia-cursorrules-prompt-file задаёт стандарты работы с Pinia и TypeScript во Vue 3: разделение состояния, синтаксис setup-хранилищ, типизацию, SSR и правила персистентности. CX Codex +1 ★ 41 178звёзд репо vue-pinia-best-practices github.com/vuejs-ai Скилл vue-pinia-best-practices с лучшими практиками Pinia: как избежать ошибок при настройке хранилищ, сохранить реактивность и правильно организовать state management в Vue-проекте. CX Codex +1 18 500установок unit-test-vue-pinia официальный github Скилл unit-test-vue-pinia для GitHub Copilot — помогает писать и проверять юнит-тесты для Vue 3, TypeScript, Vitest и Pinia. Держит тесты на публичных входах, не проваливаясь во внутренности компонентов. CX Codex +1 1 800установок pinia-skilld skilld-dev Скилл pinia-skilld для ИИ-агентов, который подсказывает верные API Pinia 4.x: хранилища, геттеры, действия, SSR и миграцию с v2 и v3. CX Codex +1 349установок

Из того же набора138

Весь набор →
nextjs Скилл для работы с Next.js 16, React 19.2 и современными паттернами серверных компонентов, Server Actions и кэширования. Помогает при миграции с версии 15, ошибках async params и настройке Partial Prerendering. CX Codex +1 299установок feature-dev Скилл feature-dev для Claude Code ведёт разработку функции через семь фаз — от изучения кодовой базы до проверки результата. Охватывает многофайловые задачи и спорные архитектурные решения. CX Codex +1 294установок cloudflare-nextjs Скилл cloudflare-nextjs для Claude Code настраивает и развёртывает Next.js на Cloudflare Workers через OpenNext. Помогает переносить проект и разбирать ошибки среды Workers. CX Codex +1 267установок cloudflare-turnstile Скилл cloudflare-turnstile для Claude Code помогает добавить Turnstile и проверять токены на сервере. Подключается при настройке защиты форм или разборе ошибок виджета. CX Codex +1 261установок base-ui-react Скилл base-ui-react помогает собирать интерфейсы на MUI Base UI: настраивать доступные компоненты и плавающие элементы, а также переносить проект с Radix UI. CX Codex +1 259установок auto-animate Скилл показывает, как подключить @formkit/auto-animate в React для списков, аккордеонов и toast-уведомлений — анимация без конфигов, 3.28 КБ. CX Codex +1 257установок hono-routing Скилл hono-routing для работы с Hono: маршруты, middleware, валидация через Zod или Valibot, RPC-клиент с выводом типов. Помогает избежать 12 типичных ошибок при построении API. CX Codex +1 256установок github-project-automation Скилл github-project-automation для Claude Code помогает настроить GitHub Actions, шаблоны задач и проверку безопасности репозитория. Также помогает искать ошибки в YAML и workflow. CX Codex +1 1установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой