Vue.js & Composition API (50 Qs)•Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)
State Persistence and Plugins in Pinia.
senior LevelCode ExampleState ManagementSystem DesignVue & Nuxt
In Simple Words:
Pinia plugins extend stores with cross-cutting concerns like persistence, logging, and error tracking. The $subscribe API listens for mutations and saves state to localStorage or sessionStorage.
typescript
import { PiniaPluginContext } from 'pinia';
export function piniaLocalStoragePlugin({ store }: PiniaPluginContext) {
const storageKey = `pinia_${store.$id}`;
const savedState = localStorage.getItem(storageKey);
if (savedState) {
store.$patch(JSON.parse(savedState));
}
// Subscribe to changes and persist automatically
store.$subscribe((mutation, state) => {
localStorage.setItem(storageKey, JSON.stringify(state));
});
}
// In main.ts:
// const pinia = createPinia();
// pinia.use(piniaLocalStoragePlugin);