Pinia 05 ๐ Actions & Async Workflows โ Writing synchronous/asynchronous actions, handling loading/error states, and calling cross-store actions
Actions are the functional heart of a Pinia store. While state represents the “what” and getters represent the “derived what,” actions represent the “how.” They are the methods where business logic, state mutations, and side effects reside. In the previous era of Vuex, developers were forced to separate logic into “actions” (for async work) and “mutations” (for synchronous state changes). Pinia removes this artificial boundary entirely. In Pinia, actions are versatile functions that can be synchronous or asynchronous, can modify state directly, and can even orchestrate complex workflows involving multiple stores.
The most common use case for actions is handling asynchronous data fetching. Modern web applications spend a significant amount of time communicating with APIs, and actions provide a centralized place to manage these network requests. By placing API logic inside an action, you ensure that the component triggering the request doesn’t need to know about headers, endpoints, or data parsing. It simply calls the action and waits for the state to update. This decoupling makes components easier to test and allows the same logic to be shared across multiple parts of the application.
This chapter explores the full lifecycle of a Pinia action. We will begin by examining the difference between synchronous and asynchronous actions and how they modify state. We will then move into the “UI Feedback Loop,” exploring how to manage loading and error states to keep the user informed during long-running tasks. Finally, we will cover inter-store communication, demonstrating how one store can call actions in another to maintain data consistency across the entire application.
Key point: Actions are the equivalent of methods in a class; they are used to define business logic and can handle both synchronous state mutations and asynchronous side effects like API calls.
Why exists
The Mutation Boilerplate problem.
In older state management libraries, you couldn’t change state directly. You had to commit a “mutation.” This meant that for a simple task like incrementing a counter, you needed an action to call a mutation, and a mutation to change the state. Actions in Pinia exist to eliminate this middleman. By allowing actions to modify state directly, Pinia reduces the amount of code you have to write and maintain without losing the ability to track changes in DevTools.
The Component Logic Bloat problem.
When components handle their own API calls and data processing, they become difficult to read. If five different components need to fetch the “User Profile,” you end up with the same fetch() logic copied five times. Actions exist to centralize this logic. Instead of components managing try/catch blocks and headers, they simply call userStore.fetchProfile(), keeping the component focused strictly on rendering.
The Async Side Effect problem.
JavaScript is inherently asynchronous, but state management needs to be predictable. Actions provide a structured environment for handling Promises, async/await, and timers. By wrapping these side effects in actions, Pinia ensures that the resulting state changes are still associated with the correct “trigger,” making debugging in the timeline much more intuitive.
The Loading/Error Synchronization problem.
Users need to know when an app is busy. Managing a isLoading variable in every single component that makes a request is error-prone. Actions allow you to manage the “meta-state” of a requestโloading flags, error messages, and timestampsโin the store. This allows multiple components to react to the same loading state simultaneously (e.g., showing a spinner in the header and a skeleton in the content area).
The Multi-Store Orchestration problem.
Features often span multiple domains. Logging out a user might require clearing the AuthStore, resetting the CartStore, and stopping a timer in the SessionStore. Actions exist as the “orchestrators” of these complex workflows. Because actions can import and call other stores, they act as the glue that keeps disparate pieces of the application in sync during major state transitions.
The Testability problem.
Testing business logic inside a Vue component requires mounting the component, which is slow and complex. Actions are just functions. By moving logic into actions, you can write unit tests that verify your business rules (e.g., “users cannot add more than 10 items to a cart”) without ever needing to render a DOM element.
a. Synchronous vs. Asynchronous Actions
In Pinia, the distinction between synchronous and asynchronous actions is purely a matter of whether the function returns a Promise (usually via the async keyword). Both types can modify the state directly.
In Option Stores, actions are methods on the actions object. They access the state and other actions using this.
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
// Synchronous action
increment() {
this.count++;
},
// Asynchronous action
async incrementWithDelay() {
await new Promise(resolve => setTimeout(resolve, 1000));
this.increment(); // Calling another action
}
}
});
In Setup Stores, actions are simply functions defined within the store factory.
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
function increment() {
count.value++;
}
async function incrementWithDelay() {
await someTimer();
increment();
}
return { count, increment, incrementWithDelay };
});
The beauty of Pinia actions is that they are fully aware of this (in Option stores) or the local closure (in Setup stores). You don’t need to pass the state as an argument; it is simply “there.” This makes actions feel like standard object-oriented methods or standard JavaScript functions, lowering the learning curve significantly.
b. Managing Loading and Error States
When performing asynchronous work, the store shouldn’t just hold the result of the data; it should also hold the status of the operation. A robust action follows a “Request-Success-Failure” pattern. By storing loading and error state, your components can automatically show spinners or error alerts.
export const useUserStore = defineStore('user', {
state: () => ({
profile: null,
loading: false,
error: null as string | null,
}),
actions: {
async fetchProfile(userId: string) {
this.loading = true;
this.error = null; // Clear previous errors
try {
const response = await api.get(`/users/${userId}`);
this.profile = response.data;
} catch (err: any) {
this.error = err.message || 'Failed to fetch profile';
// Optional: re-throw if the component needs to know
throw err;
} finally {
this.loading = false; // Always stop loading
}
}
}
});
In the component, you can now use these flags to drive the UI:
<template>
<div v-if="userStore.loading">Loading...</div>
<div v-else-if="userStore.error">{{ userStore.error }}</div>
<div v-else-if="userStore.profile">
<h1>{{ userStore.profile.name }}</h1>
</div>
</template>
This pattern ensures that your UI is never in an ambiguous state. By keeping the loading flag in the store, if the user navigates away and then back to the page while the request is still pending, the new component will immediately see that the store is loading: true and show the spinner.
c. Orchestration: Calling Cross-Store Actions
Complex applications often require stores to communicate. For example, a CartStore.checkout() action might need to check the UserStore.isLoggedIn state and, if successful, trigger a NotificationStore.notify() action.
In Pinia, you call another store simply by instantiating it inside the action. Pinia handles the singleton nature of the stores, so calling useAuthStore() inside an action gives you the same reactive instance used everywhere else.
import { useAuthStore } from './auth';
import { useNotificationStore } from './notifications';
export const useCartStore = defineStore('cart', {
state: () => ({ items: [] }),
actions: {
async purchase() {
const auth = useAuthStore();
const notify = useNotificationStore();
if (!auth.isLoggedIn) {
notify.show('Please log in to purchase', 'error');
return;
}
try {
await api.post('/checkout', this.items);
this.items = []; // Clear cart
notify.show('Purchase successful!', 'success');
} catch (e) {
notify.show('Checkout failed', 'error');
}
}
}
});
This “Orchestration” capability is what makes Pinia so powerful for enterprise-level apps. You can maintain small, focused stores (Domain-Driven Design) while still allowing them to collaborate on cross-cutting concerns. It is generally a best practice to keep cross-store calls inside actions rather than getters, as actions are designed to handle logic and flow, whereas getters should be strictly for data derivation.
Complete Example Session
// ============================================
// PART 1: EXTERNAL STORES
// ============================================
const useAuthStore = defineStore('auth', {
state: () => ({ token: 'xyz123' })
});
// ============================================
// PART 2: DATA STORE DEFINITION
// ============================================
export const usePostStore = defineStore('posts', {
state: () => ({
posts: [],
loading: false,
error: null
}),
// ============================================
// PART 3: ASYNC FETCH ACTION
// ============================================
actions: {
async fetchAll() {
this.loading = true;
try {
const res = await fetch('https://api.example.com/posts');
this.posts = await res.json();
} catch (e) {
this.error = "Failed to load posts";
} finally {
this.loading = false;
}
},
// ============================================
// PART 4: ACTION WITH ARGUMENTS
// ============================================
async deletePost(id: number) {
// Direct mutation in sync block
const index = this.posts.findIndex(p => p.id === id);
if (index !== -1) {
await fetch(`/posts/${id}`, { method: 'DELETE' });
this.posts.splice(index, 1);
}
},
// ============================================
// PART 5: CROSS-STORE ORCHESTRATION
// ============================================
async secureUpload(data: any) {
const auth = useAuthStore();
if (!auth.token) throw new Error("Unauthorized");
await fetch('/upload', {
headers: { Authorization: auth.token },
body: JSON.stringify(data)
});
},
// ============================================
// PART 6: SYNC REFRESH LOGIC
// ============================================
clearPosts() {
this.posts = [];
this.error = null;
},
// ============================================
// PART 7: BATCH UPDATES IN ACTION
// ============================================
resetAndFetch() {
this.clearPosts();
return this.fetchAll();
},
// ============================================
// PART 8: ERROR HANDLING FLOW
// ============================================
async handleRequest(fn: Function) {
try {
return await fn();
} catch (e) {
this.error = e.message;
}
},
// ============================================
// PART 9: CONDITIONAL LOGIC
// ============================================
async fetchIfEmpty() {
if (this.posts.length === 0) {
await this.fetchAll();
}
},
// ============================================
// PART 10: COMPLEX TRANSFORMATIONS
// ============================================
sortPostsByTitle() {
this.posts.sort((a, b) => a.title.localeCompare(b.title));
}
}
});
The parts above showcase a complete Post management system, handling API requests, error states, secure headers from other stores, and internal logic for clearing or sorting data.
Quick Reference
Action Patterns
| Pattern | Logic | Purpose |
|---|---|---|
| Sync | this.key = val | Immediate state update |
| Async | await somePromise() | Side effects (API, Timers) |
| Wrapped | try { ... } finally { ... } | Safe loading state management |
| Orchestrated | const other = useOther() | Inter-store communication |
Setup vs. Option Actions
| Feature | Option Store | Setup Store |
|---|---|---|
| Syntax | methods on object | Standard functions |
| State Access | this.propertyName | variableName.value |
| Action Access | this.otherAction() | otherFunction() |
| Context | Bound to this | Lexical scope (Closure) |
Common UI State Flags
| Property | Initial Value | Updated In |
|---|---|---|
loading | false | try { loading = true } |
error | null | catch (e) { error = e } |
data | null / [] | this.data = response |
lastFetch | null | this.lastFetch = Date.now() |
Best Practices
โ Do This:
// Use async/await for cleaner asynchronous code
async fetch() { this.data = await api.get(); } // โ
// Always manage loading states inside the action
async fetch() { this.loading = true; ... this.loading = false; } // โ
// Re-throw errors if the component needs local handling
catch(e) { this.error = e; throw e; } // โ
// Keep actions focused on logic, not UI concerns
// (Don't pass 'event' objects to actions) // โ
โ Don’t Do This:
// Don't use .then() chains if async/await is available
api.get().then(res => { this.data = res; }); // โ
// Don't leave loading states as true on error
// (Always use 'finally' block) // โ
// Don't use arrow functions for actions in Option stores
// (It breaks the 'this' context) // โ
// Don't perform state mutations inside components
// (Move logic to actions for better tracking) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | Action calls a getter that triggers the action | Decouple logic or use a guard flag |
this is undefined | Arrow function used in Option Store | Use actionName() { ... } syntax |
| UI Hangs on Error | loading = false missed in catch block | Use a finally block for clean-up |
| Stale Other Store | Calling useOtherStore() outside action | Always instantiate stores inside the action |
| Race Conditions | Multiple async calls updating same state | Use a “last request ID” check or abort controller |
| Missing Reactivity | Destructuring actions from Setup Store | Actions are functions; they don’t need storeToRefs |
Real-World Examples
1. Login Flow
async login(creds) { this.user = await authApi.post(creds); }
2. Paginated Fetch
async fetchPage(p) { this.items = await api.get(`/items?page=${p}`); }
3. Toggle Boolean State
toggleSidebar() { this.isOpen = !this.isOpen; }
4. Undo/Redo Logic
undo() { if (this.history.length) this.state = this.history.pop(); }
5. Search Debouncing
search(q) { clearTimeout(this.timer); this.timer = setTimeout(() => this.exec(q), 300); }
6. Form Submission
async submit() { await api.post('/form', this.formData); this.$reset(); }
7. Polling Data
startPolling() { this.interval = setInterval(() => this.fetch(), 5000); }
8. App Initialization
async init() { await Promise.all([this.fetchUser(), this.fetchTheme()]); }
9. Clear All Stores
logout() { useCart().$reset(); useUser().$reset(); router.push('/'); }
10. Optimistic UI Update
add(item) { this.items.push(item); api.save(item).catch(() => this.items.pop()); }
Visual
The Async Action Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ COMPONENT TRIGGERS ACTION โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 1. store.fetchData()
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PINIA ACTION EXECUTION โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ this.loading = true; โ โ
โ โ try { โ โ
โ โ this.data = await api.call(); (ASYNC WAIT) โ โ
โ โ } catch { โ โ
โ โ this.error = "Failed"; โ โ
โ โ } finally { โ โ
โ โ this.loading = false; โ โ
โ โ } โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 2. State changes trigger UI re-render
โผ
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโ
โ Spinner Hides โ โ Data Appears โ โ Error? โ
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโ
Cross-Store Orchestration
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ
โ Product Store โ โ Auth Store โ
โ Action: buy() โโโโโโโโค State: token โ
โโโโโโโโโโโฌโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ
โ
โ (Use Token)
โผ
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ
โ Notification โ โ External API โ
โ Action: show() โโโโโโโโค POST /order โ
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ
โฒ โ
โ (On Success/Fail) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
UI Feedback States
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STORE STATE FLAGS โ
โ โ
โ [ Idle ] => loading: false, error: null, data: null โ
โ [ Busy ] => loading: true, error: null, data: null โ
โ [ Success ] => loading: false, error: null, data: [...] โ
โ [ Failure ] => loading: false, error: "X", data: null โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Purpose | Business logic & side effects |
| Mutations | Handled directly in actions |
| Async Support | Native (async/await) |
this Context | Option Stores (Required) |
| Closure Context | Setup Stores |
| Error Pattern | try / catch / finally |
| Inter-store | Call useOtherStore() inside action |
| Optimization | Keep logic out of components |
Key takeaways:
- Actions eliminate the need for mutations. Unlike Vuex, Pinia allows actions to modify state directly, which reduces boilerplate and simplifies the flow of data .
- Asynchronous work is native. By using
async/await, actions provide a clean way to handle API calls, timers, and other side effects while keeping the UI in sync . - Meta-state is best managed in the store. Storing
loadinganderrorflags in the store ensures that all components have a consistent view of a request’s status . - Orchestration allows stores to collaborate. Actions can instantiate other stores to access their state or call their actions, enabling complex, cross-domain workflows .
- The
finallyblock is essential. Always usefinallyto reset loading flags, ensuring the UI doesn’t get stuck in a “loading” state if a network request fails . - Actions are standard functions. They don’t require special helpers like
storeToRefsto be destructured in components; they can be pulled directly from the store object .
Remember: Actions are where your application “does things.” Use them to hide the complexity of the outside world (APIs, timers, other stores) from your components, providing a clean, simple, and reactive interface for your UI to interact with your data.
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!