Intermediate LevelVue JS
How do you use store.$onAction to monitor, log, or intercept Pinia store actions?
❓ Interview Prompt: Explain Pinia action subscriptions (store.$onAction), intercepting action invocations, after resolution hooks, and onError handlers.
Pinia allows subscribing to store action executions using 'store.$onAction()'.
Action Lifecycle Hooks:
•
'name' / 'args': Name of action and passed parameter arguments.
•
'after(callback)': Fired after the action successfully resolves.
•
'onError(callback)': Fired if the action throws an error or rejects a Promise. Ideal for global error logging telemetry!
Code Implementation Example
javascript
import { useUserStore } from '@/stores/userStore';
const userStore = useUserStore();
// Subscribe to all actions executed on userStore
const unsubscribe = userStore.$onAction(({ name, args, after, onError }) => {
console.log(`Action "${name}" initiated with args:`, args);
after((result) => {
console.log(`Action "${name}" completed successfully!`);
});
onError((error) => {
console.error(`Action "${name}" failed:`, error);
});
});💡Monitoring and intercepting Pinia store action execution using store.$onAction.
🎯 Interview Key Takeaway
Use store.$onAction() to attach middleware hooks that trigger before, after, or upon failure of Pinia actions.
#Pinia#$onAction#Telemetry#Intermediate
Back to all Vue JS Questions→