Composing Stores, TypeScript, and Plugins

Learn to organize multiple Pinia stores, use TypeScript, and extend stores with plugins for features such as state persistence.

🎯 Introduction

By the end of this article, you will know how to split and organize stores in medium to large projects, add TypeScript types, and use plugins for state persistence. We will focus on these advanced topics without repeating earlier material.


🧱 Organizing Multiple Stores

As a project grows, putting all state in one store becomes difficult to manage. Split stores by feature:

stores/
├── user.js
├── cart.js
└── settings.js

For example:

  • useUserStore: authentication state and user information
  • useCartStore: shopping cart items
  • useSettingsStore: settings such as theme and language

Each store manages its own state independently. Import other stores when you need to compose them.

Pinia does not require module configuration like Vuex. Each store is already an independent module.

⚡ Composing Stores

When business logic needs data from several stores, access other stores in an action:

stores/order.js
import { defineStore } from 'pinia';
import { useCartStore } from './cart.js';

export const useOrderStore = defineStore('order', {
    actions: {
        async submit() {
            const cart = useCartStore();

            await apiCreateOrder({ items: cart.items });
            cart.clear();
        },
    },
});
Avoid circular store imports. If A imports B and B imports A, this can lead to an infinite loop. If you need a two-way dependency, consider extracting shared state into a separate store.

🛠 Pinia and TypeScript

Pinia works well with TypeScript. Add type assertions to state where needed, and type inference handles the rest.

stores/counter.ts
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
    state: () => ({
        count: 0,
        message: '' as string,
    }),
    getters: {
        double(): number {
            return this.count * 2;
        },
    },
    actions: {
        add(n: number) {
            this.count += n;
        },
    },
});

Use it in a component:

App.vue
<script setup lang="ts">
import { useCounterStore } from './stores/counter.ts';

const counter = useCounterStore();

counter.add(5); // TypeScript checks that the argument is a number
</script>
If a state property’s inferred type is not what you need, use an as Type assertion, such as items: [] as Product[].

🔌 Extending Pinia with Plugins

Pinia plugins can add capabilities when each store is created. Common uses include logging, persistence, and debugging.

Register a plugin like this:

main.js
import { createPinia } from 'pinia';

const pinia = createPinia();

pinia.use(({ store }) => {
    console.log('Store created: ', store.$id);
});

app.use(pinia);
The plugin runs once when each store is created. The store argument is the current store instance.

💾 How State Persistence Works

A common plugin requirement is saving state to localStorage so it survives page reloads. The core approach has two steps:

  1. When a store is created, read its previously saved state from localStorage.
  2. When state changes, write the new state back to localStorage.
plugins/persist.js
export function piniaPersistPlugin({ store }) {
    const key = `pinia-${store.$id}`;
    const saved = localStorage.getItem(key);

    if (saved) {
        store.$patch(JSON.parse(saved));
    }

    store.$subscribe((mutation, state) => {
        localStorage.setItem(key, JSON.stringify(state));
    });
}

Register the plugin:

main.js
import { piniaPersistPlugin } from './plugins/persist.js';

pinia.use(piniaPersistPlugin);
This is a simplified example. For production, consider pinia-plugin-persistedstate, which offers more robust support for choosing persisted properties, customizing storage, and more.

❓ Questions and Answers

Q1: Does Pinia still need modules configuration like Vuex?

No. Each store is an independent module; simply split stores by feature.

Q2: What happens if two stores reference each other?

This can cause a circular dependency and runtime errors. Consider extracting shared state into a third store.

Q3: What is $subscribe?

It is a store instance method that observes state changes, useful for persistence, logging, and similar plugin features.

Q4: Should all state be persisted?

No. Avoid persisting sensitive information, temporary state, or large lists. Persist only data that truly needs to survive navigation between pages.


🧪 Exercise

Complete the following useSettingsStore to switch themes with TypeScript:

  1. Give theme the type 'light' | 'dark' and an initial value of 'light'.
  2. Add a toggleTheme() action that switches between the two themes.
stores/settings.ts
import { defineStore } from 'pinia';

type Theme = 'light' | 'dark';

export const useSettingsStore = defineStore('settings', {
    state: () => ({
        // Define theme here
    }),
    actions: {
        toggleTheme() {
            // Write your code here
        },
    },
});

🎉 You have completed the Pinia course! From installation to composing stores, TypeScript, and plugins, you now have the skills to use Pinia confidently in Vue 3 projects.