Composing Stores, TypeScript, and Plugins
🎯 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 informationuseCartStore: shopping cart itemsuseSettingsStore: settings such as theme and language
Each store manages its own state independently. Import other stores when you need to compose them.
⚡ Composing Stores
When business logic needs data from several stores, access other stores in an action:
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();
},
},
});
🛠 Pinia and TypeScript
Pinia works well with TypeScript. Add type assertions to state where needed, and type inference handles the rest.
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:
<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>
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:
import { createPinia } from 'pinia';
const pinia = createPinia();
pinia.use(({ store }) => {
console.log('Store created: ', store.$id);
});
app.use(pinia);
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:
- When a store is created, read its previously saved state from
localStorage. - When state changes, write the new state back to
localStorage.
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:
import { piniaPersistPlugin } from './plugins/persist.js';
pinia.use(piniaPersistPlugin);
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:
- Give
themethe type'light' | 'dark'and an initial value of'light'. - Add a
toggleTheme()action that switches between the two themes.
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.
