Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Plugins and Persistence

Extending Stores from Plugins

Extend every Pinia store from a plugin: add new state, methods and non-reactive properties, hook into actions and state changes, and declare custom options.

A plugin that adds a plain string to each store is a nice start, but real plugins do more. They add reactive state that DevTools can see, wrap actions to measure them, watch state changes and react to custom options. This lesson shows each technique and explains the small rules that keep them working, including with server-side rendering.

Three kinds of additions

Whatever you add in a plugin falls into one of three groups:

  1. Plain properties and methods: values that never change or functions. Return them or assign them.
  2. Reactive state: values that components render and that belong in store.$state, so DevTools, SSR and persistence know about them.
  3. Non-reactive external objects: a router, a database client, a logger. Wrap these in markRaw() so Vue does not try to make them reactive.
JavaScript
import { markRaw } from "vue";
import { router } from "./router";

pinia.use(({ store }) => {
  store.router = markRaw(router);
});

Every action in every store can now say this.router.push("/login"). Without markRaw, Vue would wrap the router in a deep reactive proxy, which is slow and can break it.

Adding reactive state

To add state that behaves like state, put the ref in both places: in store.$state and on the store itself.

JavaScript
import { ref, toRef } from "vue";

pinia.use(({ store }) => {
  if (!Object.prototype.hasOwnProperty.call(store.$state, "hasError")) {
    const hasError = ref(false);
    store.$state.hasError = hasError;
  }
  store.hasError = toRef(store.$state, "hasError");
});

Why both? Putting it in $state makes it part of the serialized state (DevTools, SSR hydration, persistence). The toRef link makes store.hasError and store.$state.hasError the same value. The hasOwnProperty check matters during hydration: the server may have sent state that already contains hasError, and you must not overwrite it with false.

Here is a plugin that adds a loading flag to every store, plus an $onAction hook (next section) that flips it automatically while an async action runs:

A plugin that adds reactive loading state

The store never declared loading, yet it exists, is reactive and appears in $state.

Hooking into actions with $onAction

Inside a plugin you can call the same store methods a component can. store.$onAction(callback) runs before every action of that store. The callback receives:

  • name: the action name,
  • args: the arguments array,
  • store: the store,
  • after(cb): runs when the action finishes (receives the result; waits for returned promises),
  • onError(cb): runs if the action throws or a returned promise rejects.

That is everything you need for timing, logging and error reporting:

Timing every action in every store

The sibling method $subscribe is what the persistence lesson uses to save state.

Watching state with $subscribe

store.$subscribe(callback) runs after every state change. The callback gets a mutation (with storeId, type and, in development, events) and the new state. By default the subscription is removed when the component that created it unmounts. In a plugin there is no component, so it lives as long as the store. That is exactly what persistence plugins rely on.

JavaScript
pinia.use(({ store }) => {
  store.$subscribe((mutation, state) => {
    console.log(mutation.storeId, "changed", mutation.type);
  });
});

Custom options

A store can carry extra options that only your plugin understands. Plugins read them from options:

JavaScript
const useDraftStore = defineStore("draft", {
  state: () => ({ text: "" }),
  autosave: { delay: 500 },
});

pinia.use(({ store, options }) => {
  if (options.autosave) {
    // set up debounced saving using options.autosave.delay
  }
});

In TypeScript you declare the new option by augmenting Pinia's interface:

TypeScript
import "pinia";

declare module "pinia" {
  export interface DefineStoreOptionsBase<S, Store> {
    autosave?: { delay: number };
  }
  export interface PiniaCustomProperties {
    hasError: import("vue").Ref<boolean>;
  }
  export interface PiniaCustomStateProperties<S> {
    hasError: boolean;
  }
}

PiniaCustomProperties types things you add to the store, PiniaCustomStateProperties types things you add to the state, and DefineStoreOptionsBase types custom options.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you wrap a router instance in markRaw() before adding it to a store?

    markRaw tells Vue to skip reactivity for that object, which is correct and faster for external objects like routers and clients.
  2. 2. To add reactive state from a plugin so it is part of the serialized state, you should...

    Adding it to $state makes it serializable; the toRef link keeps store.x and store.$state.x identical.
  3. 3. What does after() inside $onAction do?

    after(cb) runs once the action has finished, after any returned promise has resolved.
  4. 4. Why check hasOwnProperty before adding state in a plugin?

    During hydration the state may already contain the key, and replacing it would lose the server value.

Summary

  • Plugins can add plain properties, reactive state and external objects.
  • Use markRaw() for routers, clients and other non-reactive objects.
  • Add reactive state to store.$state and link it with toRef; guard with hasOwnProperty.
  • $onAction gives you name, args, after and onError for logging, timing and error handling.
  • $subscribe in a plugin lives as long as the store.
  • Custom options are read from options; TypeScript needs module augmentation.

Next: Persisting State: the Basics