Pinia 06 ๐ Subscriptions ($subscribe & $onAction) โ Watching state mutations and intercepting actions for logging, analytics, or side effects
In a state management system, simply storing and modifying data is often only half the battle. As applications scale, developers frequently need to react to changes in state or the execution of specific logic without hardcoding that secondary logic directly into the store’s core actions. Pinia provides two powerful mechanisms for this: $subscribe and $onAction. These “subscription” methods allow you to observe the store from the outside, creating a clean separation between the data management and the side effects that result from it.
Subscriptions are essentially “listeners” that hook into the internal life cycle of the store. While Vueโs native watch() can observe reactive state, Piniaโs $subscribe is specifically optimized for state changes within the store, often triggering once per “patch” rather than for every individual property update. On the other hand, $onAction allows you to intercept the start, success, or failure of an asynchronous action. This is invaluable for cross-cutting concerns like telemetry, error reporting, and complex UI feedback that shouldn’t clutter the business logic of the store itself.
This chapter details how to implement both state and action subscriptions. We will explore how to use these tools for automatic LocalStorage persistence, how to create global logging systems that track user behavior, and how to handle the “detachment” of subscriptions to prevent memory leaks. By the end of this tutorial, you will understand how to turn your Pinia stores into reactive hubs that intelligently communicate with the rest of your application infrastructure.
Key point: Pinia subscriptions ($subscribe and $onAction) enable developers to decouple side effects like persistence, logging, and analytics from core business logic by intercepting state changes and action lifecycles.
Why exists
The Persistence Problem. Manual synchronization between state and LocalStorage is error-prone. If you have to call localStorage.setItem inside every action that modifies state, your store becomes repetitive and fragile. $subscribe exists to automate this: you define a single listener that saves the state whenever it changes, ensuring the “Source of Truth” and the “Storage” remain in sync without manual intervention.
The Debugging and Traceability Problem. In large teams, itโs hard to know exactly which action triggered a specific UI change or where a bug originated. $onAction allows you to build a global logger that records the name of every action called, the arguments passed to it, and whether it succeeded or failed. This creates a clear “audit trail” that makes debugging complex state transitions significantly easier.
The Analytics and Telemetry Problem. Marketing and product teams often need to track specific user interactions (e.g., “User added item to cart”). Instead of polluting your clean store actions with tracking scripts from Google Analytics or Mixpanel, you can use $onAction to listen for those events and fire off analytics pings in the background, keeping your store code focused purely on state management.
The Cross-Store Synchronization Problem. Sometimes, an action in UserStore needs to trigger a reset in CartStore. While you can call one store from another, doing so creates tight coupling. Subscriptions allow a third-party utility to watch for specific actions and orchestrate the interaction between stores, maintaining a cleaner architectural boundary.
The Global Error Handling Problem. Asynchronous actions can fail in many ways (network errors, 404s, validation errors). While try/catch inside actions is standard, $onAction provides an onError hook. This allows you to create a global error reporting system that automatically sends action failures to services like Sentry without needing to add error-reporting code to every single action in your project.
The Middleware Trade-off. Unlike traditional Redux middleware which can be complex to configure, Pinia subscriptions are lightweight and “opt-in.” They provide the benefits of a middleware layerโinterception and observationโwith a much simpler API that feels native to the Vue ecosystem.
a. The $subscribe Method (State Monitoring)
The $subscribe method allows you to watch the state of a store and react to changes. It is fundamentally similar to Vueโs watch(), but with a key difference: it only triggers after a mutation is complete. If you use $patch to change multiple properties at once, the subscription will only fire once, making it more performant for bulk updates.
const cartStore = useCartStore();
cartStore.$subscribe((mutation, state) => {
// mutation.type: 'direct', 'patch object', or 'patch function'
// mutation.storeId: 'cart'
// mutation.payload: the object passed to $patch (if applicable)
console.log(`State in ${mutation.storeId} changed!`);
localStorage.setItem('cart-backup', JSON.stringify(state));
});
By default, subscriptions are bound to the component where they are created. This means if you call $subscribe inside a componentโs setup(), the subscription will automatically be cleaned up (unsubscribed) when that component is unmounted. This is a critical safety feature that prevents memory leaks and “ghost” logic from running after a view has been destroyed.
If you need a subscription to persist even after the component is gone (for example, a background sync service), you can pass { detached: true } as the second argument. This makes the subscription “global” to the applicationโs lifecycle until the app itself is unmounted or you manually call the returned unsubscribe function.
// This subscription lives on even after the component dies
const unsubscribe = cartStore.$subscribe(
(mutation, state) => { /* logic */ },
{ detached: true }
);
// Call this later to stop the subscription manually
// unsubscribe();
b. The $onAction Method (Action Interception)
While $subscribe looks at the data, $onAction looks at the logic. It allows you to wrap a storeโs actions with your own code. This is a “hook-based” system where you can run code before the action starts, after it successfully finishes, or when it throws an error.
const userStore = useUserStore();
userStore.$onAction(({ name, store, args, after, onError }) => {
// name: the name of the action being called (e.g., 'login')
// args: the array of arguments passed to the action
console.log(`Action "${name}" started with args:`, args);
after((result) => {
// Triggers if the action completes or returns a resolved promise
console.log(`Action "${name}" finished successfully with result:`, result);
});
onError((error) => {
// Triggers if the action throws an error or returns a rejected promise
console.warn(`Action "${name}" failed with error:`, error.message);
});
});
The after and onError hooks are particularly powerful for asynchronous actions (Actions using async/await). Pinia intelligently waits for the returned Promise to resolve or reject before triggering these hooks. This allows you to track “Pending” states for your UI or log the exact duration of an API call by capturing the start time before the after hook executes.
Similar to $subscribe, action subscriptions are component-bound by default. If you want an action logger to run globally for the entire duration of the app, you must pass true as the second argument to $onAction to detach it from the current component instance.
c. Real-World Persistence & Cleanup
One of the most common uses for $subscribe is LocalStorage persistence. However, a naive implementation can lead to performance issues if the state is very large. Best practices involve using the mutation object to filter which changes should trigger a save, or using a “debounced” function to ensure you aren’t writing to disk hundreds of times per second during a rapid user interaction.
import { debounce } from 'lodash-es';
const authStore = useAuthStore();
// Debounced subscription for performance
const persist = debounce((state) => {
localStorage.setItem('auth_state', JSON.stringify(state));
}, 1000);
authStore.$subscribe((mutation, state) => {
persist(state);
});
Manual cleanup is the other side of the coin. Every subscription returns a function. If you are creating subscriptions dynamically (e.g., based on a user selecting a specific item to “watch”), you must store these functions and call them when they are no longer needed. Failure to do so can result in multiple duplicate listeners running simultaneously, causing unexpected UI behavior and slowing down the main thread.
const activeSubscriptions = new Map();
function watchStore(id) {
const store = useDynamicStore(id)();
// Cleanup old one if it exists
if (activeSubscriptions.has(id)) {
activeSubscriptions.get(id)();
}
const unsubs = store.$subscribe((mut, state) => {
console.log(`Watching store ${id}`);
});
activeSubscriptions.set(id, unsubs);
}
Complete Example Session
// ============================================
// PART 1: THE STORE DEFINITION
// ============================================
export const useTaskStore = defineStore('tasks', {
state: () => ({ items: [], loading: false }),
actions: {
async addTask(text) {
this.loading = true;
// Simulate API delay
await new Promise(r => setTimeout(r, 1000));
if (text === 'error') throw new Error('Invalid Task');
this.items.push(text);
this.loading = false;
return 'Success';
}
}
});
// ============================================
// PART 2: STATE SUBSCRIPTION (Logging)
// ============================================
const tasks = useTaskStore();
tasks.$subscribe((mutation, state) => {
console.log('Mutation Type:', mutation.type); // 'direct'
console.log('New Item Count:', state.items.length);
});
// ============================================
// PART 3: ACTION SUBSCRIPTION (Analytics)
// ============================================
tasks.$onAction(({ name, args, after, onError }) => {
const startTime = Date.now();
if (name === 'addTask') {
console.log(`Analytics: User attempting to add task "${args[0]}"`);
}
after(() => {
const duration = Date.now() - startTime;
console.log(`Performance: Action ${name} took ${duration}ms`);
});
onError((err) => {
console.error(`Sentry: Action ${name} failed!`, err);
});
});
// ============================================
// PART 4: DETACHED SUBSCRIPTION (Persistence)
// ============================================
tasks.$subscribe((mutation, state) => {
localStorage.setItem('saved_tasks', JSON.stringify(state.items));
}, { detached: true });
// ============================================
// PART 5: CONDITIONAL MUTATION HANDLING
// ============================================
tasks.$subscribe((mutation) => {
if (mutation.type === 'patch object') {
console.log('Bulk update detected via $patch({...})');
}
});
// ============================================
// PART 6: PREVENTING INFINITE LOOPS
// ============================================
tasks.$subscribe((mutation, state) => {
// โ NEVER MODIFY THE STATE DIRECTLY INSIDE $subscribe
// state.items.push('loop'); // This would trigger $subscribe again!
});
// ============================================
// PART 7: MANUAL UNSUBSCRIBE
// ============================================
const stopWatching = tasks.$onAction(({ name }) => {
console.log('Running temporary action logger...');
});
// ... later
stopWatching();
// ============================================
// PART 8: ACCESSING THE STORE INSTANCE
// ============================================
tasks.$onAction(({ store }) => {
// You have access to the whole store instance
console.log('Store ID:', store.$id);
});
// ============================================
// PART 9: SUBSCRIPTIONS IN PLUGINS (Global)
// ============================================
// Inside a pinia plugin
// pinia.use(({ store }) => {
// store.$subscribe(...)
// })
// ============================================
// PART 10: ACTION ARGS VALIDATION
// ============================================
tasks.$onAction(({ args }) => {
if (args[0] === '') console.warn('Empty task added!');
});
This sequence demonstrates the core API for watching state, intercepting actions with performance tracking, handling errors, and managing subscription lifecycles.
Quick Reference
Subscription Types
| Feature | Method | Best For | Triggers On |
|---|---|---|---|
| State | $subscribe | Persistence, local caching | Any state change |
| Action | $onAction | Analytics, logging, global errors | Action calls |
Mutation Object Properties ($subscribe)
| Property | Description |
|---|---|
type | How the state changed (direct, patch object, patch function) |
storeId | The ID of the store (useful for global listeners) |
payload | The object passed to $patch (if applicable) |
Action Context Properties ($onAction)
| Property | Description |
|---|---|
name | Name of the action being executed |
store | Reference to the store instance |
args | Array of arguments passed to the action |
after | Hook that runs after successful completion |
onError | Hook that runs if the action throws/rejects |
Best Practices
โ Do This:
// Use $subscribe for automatic persistence
store.$subscribe((mut, state) => save(state)); // โ
// Use after/onError hooks for async action tracking
store.$onAction(({ after }) => after(() => finish())); // โ
// Debounce state subscriptions to save disk I/O
const debouncedSave = debounce(s => save(s), 500); // โ
// Use detached: true for global background services
store.$subscribe(callback, { detached: true }); // โ
โ Don’t Do This:
// Modify state inside a subscription (Infinite Loop!)
store.$subscribe((mut, state) => { state.count++; }); // โ
// Put business logic inside subscriptions
store.$subscribe(() => { calculateTax(); }); // โ
// Forget to unsubscribe from manual/dynamic listeners
const unsub = store.$subscribe(...); // (Never called) // โ
// Block the main thread with heavy sync logic in $subscribe
store.$subscribe(() => { heavyComputation(); }); // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | Modifying state inside $subscribe | Never update state within a subscription listener |
| Memory Leak | detached: true used without manual cleanup | Always call the returned unsub() function when done |
| Stale Data | Subscription runs before an async action finishes | Use $onAction with the after() hook instead |
| Over-triggering | Direct state mutations firing for every keypress | Use $patch or debounce the subscription callback |
| Missing Errors | Forgetting that onError is needed for async | Always define an onError hook if logging actions |
Real-World Examples
1. Simple State Logger
store.$subscribe((m, state) => console.log('State changed:', state));
2. LocalStorage Sync
store.$subscribe((m, s) => localStorage.setItem('key', JSON.stringify(s)));
3. Action Performance Audit
store.$onAction(({ after }) => after(() => console.log('Done!')));
4. Google Analytics Event
store.$onAction(({ name }) => { if(name==='buy') track('Purchase'); });
5. Sentry Error Reporting
store.$onAction(({ onError }) => onError(err => Sentry.capture(err)));
6. Disabling UI during Action
store.$onAction(({ after }) => { ui.busy=true; after(()=>ui.busy=false); });
7. Undo/Redo History Buffer
store.$subscribe((m, state) => history.push({...state}));
8. Syncing two stores
storeA.$onAction(({ name }) => { if(name==='reset') storeB.reset(); });
9. Filtering Subscriptions
store.$subscribe((mut) => { if(mut.type === 'direct') log(); });
10. Global Action Guard
store.$onAction(({ args }) => { if(!args[0]) throw Error('Missing ID'); });
Visual
The $subscribe Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MUTATION TRIGGERED (Direct, $patch, or Action) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STATE UPDATED INTERNALLY โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ $subscribe CALLBACK FIRES (Once per mutation/patch) โ
โ - Receives 'mutation' object โ
โ - Receives current 'state' โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Action Interception Hooks
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ACTION CALLED โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ $onAction Listener triggers (Pre-execution) โ
โ โ
โ if successful: if failure: โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โ โ after() hook โ โ onError() โ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Persistence Flow
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โ Pinia โ โ $subscribe โ โ LocalStorage โ
โ Store โโโโโโโถโ Middleware โโโโโโโถโ โ
โ (Memory) โ โ (Logic) โ โ (Disk) โ
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ
โฒ โ โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโ
(Sync happens on every mutation)
Summary
| Item | Value |
|---|---|
| State Watcher | $subscribe |
| Action Watcher | $onAction |
| Mutation Types | direct, patch object, patch function |
| Persistence Pattern | $subscribe + localStorage |
| Analytics Pattern | $onAction + after() |
| Component Binding | Automatic (unless detached: true) |
| Unsubscribe method | Function returned by subscription call |
| Patching Behavior | $subscribe fires once per $patch |
Key takeaways:
- Subscriptions decouple side effects from data. By using
$subscribeand$onAction, your stores stay focused on “What the data is” while external listeners handle “What happens when it changes” . - $subscribe is for the “What”. It tracks state changes and is the primary tool for saving state to disk, syncing with databases, or updating dependent UI elements globally .
- $onAction is for the “How”. It tracks the lifecycle of business logic. Use it for performance monitoring, user behavior analytics, and robust error logging .
- Memory management is vital. Always remember that subscriptions are component-bound. If you create them outside a component or use the
detachedflag, you are responsible for calling theunsub()function to prevent leaks . - Performance matters. Use the
mutationmetadata to ignore irrelevant changes, and always consider debouncing disk-heavy operations like writing to LocalStorage . - Never update state inside a subscription. This creates infinite recursion where the change triggers the subscription, which changes the state, which triggers the subscription again .
Remember: Pinia Subscriptions are the “Observer Pattern” built directly into your state management. They provide a safe, structured way to handle logging, persistence, and analytics without cluttering your core application logic.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!