Intermediate LevelVue JS
How do you persist Pinia store state to localStorage using pinia-plugin-persistedstate?
❓ Interview Prompt: Explain Pinia store state persistence, pinia-plugin-persistedstate integration, and rehydration on app reload.
By default, Pinia store state is held in browser RAM; refreshing the page wipes all active state back to initial values.
Using 'pinia-plugin-persistedstate':
1
Register plugin on root pinia instance: 'pinia.use(createPersistedState())'.
2
Enable persistence in store definition: '{ persist: true }'.
3
The plugin automatically serializes store state to 'localStorage' on mutations and rehydrates state seamlessly on page reloads!
Code Implementation Example
javascript
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null,
token: ''
}),
actions: {
setToken(newToken) { this.token = newToken; }
},
// Automatically persists store state to localStorage and rehydrates!
persist: true
});💡Persisting Pinia store state across browser reloads using pinia-plugin-persistedstate.
🎯 Interview Key Takeaway
Configure persist: true with pinia-plugin-persistedstate to sync Pinia store state automatically with localStorage.
#Pinia#Persistence#localStorage#Intermediate
Back to all Vue JS Questions→