Pinia state management: domain stores, getters and actions (including async error state), storeToRefs, persistence plugins, typed stores, $reset in setup stores and isolated tests.
.cursor/rules/vue-state-management-with-pinia.mdc. Downloaded files need to be placed in that repository path.---
description: "Pinia state management: domain stores, getters and actions (including async error state), storeToRefs, persistence plugins, typed stores, $reset in setup stores and isolated tests."
globs: "**/*"
alwaysApply: false
---
Apply these rules when managing shared state with Pinia.
## Store design
- Create one store per domain (`useAuthStore`, `useCartStore`), not one global store. Keep component-only state in components.
- Choose one style per project: option stores (`state`, `getters`, `actions`) or setup stores (refs, computeds, functions). In setup stores, return every state ref, or devtools, SSR and plugins cannot see it.
## Getters
- Put derived values in getters (`computed` in setup stores). They are cached and update automatically; do not store derived values in state.
## Actions
- Change state through actions when the change involves rules, multiple fields or async work. Simple direct assignments from components are allowed but keep business rules in actions.
- Async actions track their own status and errors:
```ts
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
export interface CartItem { id: string; price: number; qty: number }
export const useCartStore = defineStore('cart', () => {
const items = ref<CartItem[]>([]);
const status = ref<'idle' | 'saving' | 'error'>('idle');
const lastError = ref<string | null>(null);
const total = computed(() => items.value.reduce((sum, i) => sum + i.price * i.qty, 0));
async function checkout(api: { submit(items: CartItem[]): Promise<void> }) {
status.value = 'saving';
lastError.value = null;
try {
await api.submit(items.value);
items.value = [];
status.value = 'idle';
} catch (e) {
status.value = 'error';
lastError.value = e instanceof Error ? e.message : 'Checkout failed';
}
}
function $reset() {
items.value = [];
status.value = 'idle';
lastError.value = null;
}
return { items, status, lastError, total, checkout, $reset };
});
```
## Using stores in components
- Destructure state and getters with `storeToRefs(store)`; call actions on the store directly. Plain destructuring loses reactivity.
## Persistence
- Persist only what must survive a reload (cart, preferences) with a plugin such as `pinia-plugin-persistedstate` or a small custom plugin; never persist tokens or secrets in `localStorage`.
## Types
- Setup stores infer their types; option stores need typed `state: () => ({ ... })` return values. Type API responses before they enter the store.
## Resetting
- Option stores have a built-in `$reset()`. Setup stores do not: implement `$reset` yourself (as above) and call it on logout.
## Testing
- In unit tests of a store, call `setActivePinia(createPinia())` in `beforeEach` and test actions and getters directly with fake API objects. In component tests, use `createTestingPinia()` from `@pinia/testing` to stub actions and set initial state.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
frontend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A shop app keeps cart, user and UI flags in one big Pinia store, destructures state directly in components (losing reactivity), and calls store.$reset() on logout although it is a setup store.
Apply the Vue State Management with Pinia rule to src/stores/main.ts and the components that use it.
Separate auth and cart stores, total as a getter, an async checkout action with status/lastError, a hand-written $reset in each setup store called on logout, storeToRefs in components, persistence limited to the cart, and store unit tests using setActivePinia(createPinia()).
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/vue-state-management-with-pinia.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Vue State Management with Pinia project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when managing shared state with Pinia.
## Store design
- Create one store per domain (`useAuthStore`, `useCartStore`), not one global store. Keep component-only state in components.
- Choose one style per project: option stores (`state`, `getters`, `actions`) or setup stores (refs, computeds, functions). In setup stores, return every state ref, or devtools, SSR and plugins cannot see it.
## Getters
- Put derived values in getters (`computed` in setup stores). They are cached and update automatically; do not store derived values in state.
## Actions
- Change state through actions when the change involves rules, multiple fields or async work. Simple direct assignments from components are allowed but keep business rules in actions.
- Async actions track their own status and errors:
```ts
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
export interface CartItem { id: string; price: number; qty: number }
export const useCartStore = defineStore('cart', () => {
const items = ref<CartItem[]>([]);
const status = ref<'idle' | 'saving' | 'error'>('idle');
const lastError = ref<string | null>(null);
const total = computed(() => items.value.reduce((sum, i) => sum + i.price * i.qty, 0));
async function checkout(api: { submit(items: CartItem[]): Promise<void> }) {
status.value = 'saving';
lastError.value = null;
try {
await api.submit(items.value);
items.value = [];
status.value = 'idle';
} catch (e) {
status.value = 'error';
lastError.value = e instanceof Error ? e.message : 'Checkout failed';
}
}
function $reset() {
items.value = [];
status.value = 'idle';
lastError.value = null;
}
return { items, status, lastError, total, checkout, $reset };
});
```
## Using stores in components
- Destructure state and getters with `storeToRefs(store)`; call actions on the store directly. Plain destructuring loses reactivity.
## Persistence
- Persist only what must survive a reload (cart, preferences) with a plugin such as `pinia-plugin-persistedstate` or a small custom plugin; never persist tokens or secrets in `localStorage`.
## Types
- Setup stores infer their types; option stores need typed `state: () => ({ ... })` return values. Type API responses before they enter the store.
## Resetting
- Option stores have a built-in `$reset()`. Setup stores do not: implement `$reset` yourself (as above) and call it on logout.
## Testing
- In unit tests of a store, call `setActivePinia(createPinia())` in `beforeEach` and test actions and getters directly with fake API objects. In component tests, use `createTestingPinia()` from `@pinia/testing` to stub actions and set initial state.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.