Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 38 ยท Projects and Practice

Project: An Async Data Store with Caching

Build a reusable Pinia store for server data: loading and error states per key, a time-based cache, de-duplicated requests, invalidation and optimistic updates with rollback.

Fetching data looks easy until three components ask for the same URL at once, a user clicks "refresh" five times or a failed update leaves the screen showing something untrue. Libraries such as TanStack Query exist for this, but building a small version yourself teaches the ideas, and it fits in one Pinia store. By the end you will have a store with per-key status, a time-to-live cache, request de-duplication, invalidation and optimistic updates.

The ideas

Problem Solution
Three components request the same data De-duplicate: share the one in-flight promise
Switching pages refetches everything Cache results for a time-to-live (TTL)
Data goes stale Invalidate a key after a change or on demand
Screen should show a spinner or an error Store status per key: idle, loading, success, error
Clicking "like" feels slow Optimistic update: change the screen first, undo if the server fails
flowchart TD
  A["fetch(key)"] --> B{"fresh entry in cache?"}
  B -->|"yes"| C["return cached data"]
  B -->|"no"| D{"request already running?"}
  D -->|"yes"| E["share that promise"]
  D -->|"no"| F["start request, status = loading"]
  F --> G["success: save data + time"]
  F --> H["failure: save error"]

The decision tree inside fetch.

State shape

State is a dictionary keyed by a string such as "user:1" or "posts?page=2":

JavaScript
state: () => ({
  entries: {
    // "user:1": { data, error, status, fetchedAt }
  },
}),

Plain data, no promises, so it can be serialized for SSR or persisted. The in-flight promises are not state; they live in a module-level Map, because a promise cannot be serialized and does not need to be reactive. (On a server, create that map per request; see SSR pitfalls.)

The store

JavaScript
const inflight = new Map();

const useQueryStore = defineStore("queries", {
  state: () => ({ entries: {} }),
  getters: {
    entry: (state) => (key) => state.entries[key] ?? { data: null, error: null, status: "idle", fetchedAt: 0 },
  },
  actions: {
    async fetch(key, loader, { ttl = 5000, force = false } = {}) {
      const current = this.entry(key);
      const fresh = current.status === "success" && Date.now() - current.fetchedAt < ttl;
      if (fresh && !force) return current.data;              // 1. cache hit

      if (inflight.has(key)) return inflight.get(key);       // 2. share running request

      this.entries[key] = { ...current, status: "loading", error: null };
      const promise = loader()
        .then((data) => {
          this.entries[key] = { data, error: null, status: "success", fetchedAt: Date.now() };
          return data;
        })
        .catch((error) => {
          this.entries[key] = { ...this.entries[key], error: error.message, status: "error" };
          throw error;
        })
        .finally(() => inflight.delete(key));

      inflight.set(key, promise);
      return promise;
    },
    invalidate(key) {
      if (this.entries[key]) this.entries[key].fetchedAt = 0;
    },
  },
});

Notes:

  • On a refetch, we keep the old data while status is loading (...current). The screen can show old data plus a small spinner instead of flashing empty.
  • On error, we also keep the old data; the view decides whether to show it.
  • invalidate does not delete anything: it marks the entry as stale, so the next fetch reloads it but the old data stays visible meanwhile.

Optimistic updates

For a change such as a "like", wait for the server and the button feels slow. An optimistic update shows the new value immediately and rolls back if the server rejects:

JavaScript
async mutate(key, optimisticUpdate, request) {
  const before = JSON.parse(JSON.stringify(this.entries[key].data));   // snapshot
  this.entries[key].data = optimisticUpdate(this.entries[key].data);   // show it now
  try {
    await request();
  } catch (e) {
    this.entries[key].data = before;                                    // undo
    throw e;
  } finally {
    this.invalidate(key);                                               // refetch truth later
  }
},

Running it

The fake API below takes 600 ms per call and counts how many calls actually happen. Try these experiments and watch the "network calls" counter:

  1. Press Load twice at once: two requests were asked for, only one call is made (de-duplication).
  2. Press Load again within five seconds: no call (cache hit). After five seconds: a new call.
  3. Press Force refresh: always a call.
  4. Press Like (server ok) and Like (server fails): the number changes at once; on failure it jumps back.
A query store with cache, de-duplication and optimistic updates

The counter proves the cache works: the user pressed buttons many times, the "server" was called only when needed.

Testing it

Because the loader is an argument, the store is easy to test without any network: pass a fake loader that counts calls and a controllable delay, then assert: two simultaneous fetch calls call the loader once; a second fetch inside the TTL does not call it; with force: true it does; a rejected loader sets status: "error" and keeps the old data. Use vi.useFakeTimers() to move the clock past the TTL, as shown in the mocking lesson.

Where to go next

  • Retry with backoff: on failure, retry up to three times with growing delays.
  • Stale-while-revalidate: always return cached data immediately and refresh in the background.
  • Garbage collection: remove entries not used for ten minutes.
  • Request cancellation with AbortController, so a newer request for the same key cancels the older one.
  • For production apps, compare with a dedicated library (TanStack Query for Vue, or Pinia Colada, which builds this pattern on top of Pinia).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are in-flight promises kept outside the Pinia state?

    State should be plain serializable data; a promise is neither, so it lives in a module-level map.
  2. 2. Two components call fetch('post:1', loader) at the same moment. How many loader calls happen?

    De-duplication returns the existing in-flight promise instead of starting another request.
  3. 3. What does an optimistic update do when the server fails?

    The snapshot lets the store undo the optimistic change so the screen matches the truth again.
  4. 4. What does invalidate(key) do in this store?

    It sets fetchedAt to 0, which makes the cache entry count as expired.

Summary

  • Keep status, data, error and time per key in plain state.
  • Cache with a TTL, share in-flight promises and expose force and invalidate.
  • Keep old data visible while refreshing or after an error.
  • Optimistic updates snapshot, change, request and roll back on failure.
  • Accept the loader as an argument so the store is easy to test.

Next: Pinia Best Practices and Practice Exercises