Actions and Asynchronous Operations

Learn to handle asynchronous requests, call other actions, and manage loading state in Pinia actions.

🎯 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:

stores/user.js
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:

App.vue
<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>
Use 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:

stores/counter.js
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);
        },
    },
});
Use 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:

stores/auth.js
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();
        },
    },
});
Calling 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:

  1. An articles property initialized to an empty array and loading initialized to false.
  2. A fetchArticles() action that sets loading to true, puts the mock data in articles after one second, then sets loading back to false.
stores/article.js
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.