Lesson 4 of 9 · 24m
Pinia Store Design: State, Getters, and Actions
When a store is justified, how to structure Pinia modules, and why actions should encode workflows instead of becoming grab bags.
Pinia is small enough that teams misuse it casually. The common failure mode is treating every shared value as store material and ending up with a parallel component system in stores/. Pinia is at its best when a store represents a bounded domain: cart, workspace session, draft document — something with real workflows and state transitions.
Start with the smallest store that owns the invariant
export const useCartStore = defineStore("cart", {
state: () => ({
items: [] as CartItem[],
couponCode: null as string | null,
}),
getters: {
subtotal: (state) => state.items.reduce((sum, item) => sum + item.price * item.qty, 0),
itemCount: (state) => state.items.reduce((sum, item) => sum + item.qty, 0),
},
actions: {
addItem(item: CartItem) {
const existing = this.items.find((entry) => entry.sku === item.sku);
if (existing) existing.qty += item.qty;
else this.items.push(item);
},
},
});The important design decision is addItem: the invariant "one row per SKU" lives in the store, not scattered across components. Actions are where business rules belong. If components mutate state directly, the store degenerates into shared mutable objects with no guarantees.
Setup stores are often clearer for TypeScript-heavy code
export const useSessionStore = defineStore("session", () => {
const user = shallowRef<User | null>(null);
const permissions = shallowRef<Set<string>>(new Set());
const isAdmin = computed(() => permissions.value.has("admin"));
async function load() {
const session = await fetchSession();
user.value = session.user;
permissions.value = new Set(session.permissions);
}
return { user, isAdmin, load };
});Setup stores look like composables because they are composables with registration and devtools integration. They type private helpers naturally and avoid this ambiguity. Use either style consistently per codebase; mixing styles casually makes refactors harder than either choice alone.
Do not store server data twice
If the backend owns the canonical list of invoices, Pinia should not become a handwritten cache with invalidation logic unless you truly need cross-page coordination. Often the better architecture is a dedicated server-state layer plus a small store for client-side intent: selected filters, open panels, optimistic drafts. This separation prevents "the UI said paid but the server said pending" inconsistencies.
Persist deliberately
pinia-plugin-persistedstate or handwritten persistence can be useful, but persistence is a schema migration problem. Store a version field, validate the shape on load, and clear incompatible snapshots. Users do not care that their stale localStorage broke your new checkout flow — they just see a white screen.
Field notes
- One giant
useAppStoreis a design failure. Split by invariant and workflow, not by page. - Devtools are useful only if action names and mutations reflect real operations.
setStatetells nobody anything. - Stores should be safe to use outside setup, but tests are easier if async dependencies are injected or isolated.
- Do not put non-serializable objects into persisted state. Dates, class instances, and DOM references create subtle corruption.
Was this lesson helpful?