Actions and Asynchronous Operations
🎯 Introduction
By the end of this article, you will be able to handle asynchronous operations, such as API requests, in Pinia actions. We will explain the core workflow with a minimal example and clarify what this refers to inside an action.
🧱 Why Put Asynchronous Logic in Actions?
Suppose you need to fetch user information from a backend and display it in several places. If each component sends its own request:
- Code is duplicated.
- Loading state and error handling are scattered across components.
- Components become bloated.
With the request in a store action, components only need to call a method; the store handles the rest.
🛠 Making Requests in an Action
Pinia actions support async/await, making asynchronous code straightforward:
import { defineStore } from 'pinia';
import { fetchUserInfo } from '../api/user.js';
export const useUserStore = defineStore('user', {
state: () => ({
info: null,
loading: false,
}),
actions: {
async loadUser() {
this.loading = true;
try {
const res = await fetchUserInfo();
this.info = res.data;
} finally {
this.loading = false;
}
},
},
});
Use it in a component:
<template>
<p v-if="user.loading">Loading...</p>
<p v-else>Username: {{ user.info?.name }}</p>
<button @click="user.loadUser">Load user</button>
</template>
<script setup>
import { useUserStore } from './stores/user.js';
const user = useUserStore();
</script>
this.info and this.loading to read and write state inside the action. Here, this refers to the current store instance, not the component instance.⚡ Calling Other Actions
An action can call other actions in the same store:
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
add() {
this.count++;
},
async addAndLog() {
this.add(); // Call an action in this store
console.log('Current count: ', this.count);
},
},
});
this.xxx() to call an action in the same store, just like an ordinary method.💡 Calling Across Stores
Sometimes an action needs another store’s data or methods. For example, you might refresh the shopping cart after a successful login:
import { defineStore } from 'pinia';
import { useCartStore } from './cart.js';
export const useAuthStore = defineStore('auth', {
actions: {
async login(form) {
const res = await apiLogin(form);
this.token = res.token;
const cart = useCartStore();
await cart.loadCart();
},
},
});
useCartStore() inside an action is safe because Pinia has already been registered. Avoid calling use functions directly at the top level of a store file.❓ Questions and Answers
Q1: Does this inside an action refer to the component?
No. It refers to the current store instance, so you can use this.stateName and this.actionName().
Q2: Does calling another store’s action create a new instance?
No. useXxxStore() returns a singleton; repeated calls return the same instance.
Q3: Can an action directly modify another store’s state?
Technically yes, but this is not recommended. Let that store expose actions to update its own state to keep responsibilities clear.
Q4: Must actions be asynchronous?
No. Actions can also contain synchronous logic; they are simply especially useful for asynchronous operations.
🧪 Exercise
Complete the following useArticleStore with:
- An
articlesproperty initialized to an empty array andloadinginitialized tofalse. - A
fetchArticles()action that setsloadingtotrue, puts the mock data inarticlesafter one second, then setsloadingback tofalse.
import { defineStore } from 'pinia';
function mockFetch() {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ id: 1, title: 'Getting Started with Pinia' },
{ id: 2, title: 'New Features in Vue 3' },
]);
}, 1000);
});
}
export const useArticleStore = defineStore('article', {
state: () => ({
// Define the initial state here
}),
actions: {
async fetchArticles() {
// Write your code here
},
},
});
🎉 You now know how to write asynchronous Pinia actions! Next, we will explore organizing multiple stores, TypeScript, and plugins.
