Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Getters and Actions

Async Actions and API Calls

Write async Pinia actions that call APIs, track loading and error state, avoid stale responses and double requests, and cache results. Runnable demos use a fake API.

Most real stores talk to a server. In Pinia that needs nothing special: an action can be async, await a request, and then write the result into state. What takes care is the state around the request: is it loading, did it fail, is the answer still current? This lesson builds those patterns step by step.

The live examples cannot reach a real server from the sandbox, so they use a small fake API built from timers. The store code is exactly what you would write with fetch; only the line that sends the request differs.

The basic async action

JavaScript
actions: {
  async loadUsers() {
    const res = await fetch("/api/users");
    this.users = await res.json();
  },
},

The action returns a promise, so callers can await it or use .then. Always remember that fetch does not reject on HTTP errors like 404 or 500; check res.ok yourself:

JavaScript
async loadUsers() {
  const res = await fetch("/api/users");
  if (!res.ok) throw new Error(`Server answered ${res.status}`);
  this.users = await res.json();
},

Track loading and error state

Components need to show a spinner while waiting and a message when it fails. Put both in the store, next to the data:

JavaScript
state: () => ({ users: [], loading: false, error: null }),
actions: {
  async loadUsers() {
    this.loading = true;
    this.error = null;
    try {
      this.users = await api.getUsers();
    } catch (e) {
      this.error = e.message;
    } finally {
      this.loading = false;
    }
  },
},

finally guarantees that loading returns to false whether the request succeeded or failed. Forgetting it is the most common reason for a spinner that never stops.

Loading, success and error states

(The api.failNext flag is plain, non-reactive, so the checkbox state is read once per render; that is enough for this demo.)

Let the caller handle errors, too

Swallowing the error inside the action means the caller never knows. A useful pattern is to record it in state and rethrow:

JavaScript
} catch (e) {
  this.error = e.message;
  throw e; // callers can still react, for example to navigate away
}

The caller can then write await store.load().catch(() => {}) when it does not care, or handle the failure when it does. Pick one rule for the project and stick to it.

Avoid double requests

A user double-clicks a button, or two components both call load() on mount. You do not want two identical requests. Keep the promise and reuse it while it is pending:

JavaScript
let pending = null; // module-level, not state

actions: {
  load() {
    if (pending) return pending;
    pending = this.fetchUsers().finally(() => { pending = null; });
    return pending;
  },
},

Alternatively, simply return early when this.loading is true. The promise approach is better because late callers can still await the same result.

Ignore stale responses

Typing in a search box fires a request per keystroke. The answers can come back out of order: the answer for "ab" arrives after the answer for "abc" and overwrites it. The fix is to remember which request is the latest and ignore the rest:

Ignoring out-of-order answers

Without the guard, the slow answer for "p" arrives last and shows five results for a query that is now "pin". With the guard, only the newest request may write. (For real network requests, AbortController can also cancel the old request; the ticket idea works for any async source.)

Cache results

If data rarely changes, do not reload it on every visit. A simple cache keeps what you fetched and when:

JavaScript
state: () => ({ users: [], loadedAt: 0 }),
actions: {
  async loadUsers({ maxAgeMs = 60_000 } = {}) {
    if (Date.now() - this.loadedAt < maxAgeMs) return;
    this.users = await api.getUsers();
    this.loadedAt = Date.now();
  },
},

Callers that need fresh data pass maxAgeMs: 0. For heavier needs (retries, background refresh, deduplication by key), a dedicated library such as TanStack Query for Vue is designed for server state and can work next to Pinia; the comparison lesson (Pinia vs Vuex and other options) mentions where each fits.

Calling async actions from components

VUE
<script setup>
import { useUsersStore } from "@/stores/users";
const users = useUsersStore();
await users.load(); // top-level await needs <Suspense> around the component
</script>

Without Suspense, call it in onMounted, or in a router guard so the page appears only after the data is ready. Either way the store is the same.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use try/finally around an awaited request that sets loading?

    finally runs in both cases, so the spinner cannot get stuck.
  2. 2. fetch receives a 404 response. What happens by default?

    fetch only rejects on network failure. HTTP errors resolve with ok set to false.
  3. 3. What problem does a ticket counter in a search action solve?

    Only the answer to the latest request may write, so stale replies are ignored.
  4. 4. Which approach lets late callers share one pending request?

    Reusing the same promise means every caller awaits the same request.

Summary

  • Async actions are normal async methods that write results into state.
  • Keep loading and error next to the data; use try/catch/finally.
  • Check res.ok yourself; rethrow if callers should react.
  • Reuse a pending promise to avoid duplicate requests; use a ticket to ignore stale answers.
  • A timestamp makes a simple cache.

Next: Watching Actions with $onAction