Gathering detailed insights and metrics for pinia-plugin-persistedstate-2
Gathering detailed insights and metrics for pinia-plugin-persistedstate-2
Gathering detailed insights and metrics for pinia-plugin-persistedstate-2
Gathering detailed insights and metrics for pinia-plugin-persistedstate-2
Persist and rehydrate your Pinia state between page reloads.
npm install pinia-plugin-persistedstate-2
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
95 Stars
891 Commits
9 Forks
3 Watching
8 Branches
5 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
TypeScript (98.16%)
JavaScript (1.55%)
Shell (0.29%)
Cumulative downloads
Total Downloads
Last day
-29.4%
659
Compared to previous day
Last week
-10.3%
3,718
Compared to previous week
Last month
22.5%
16,550
Compared to previous month
Last year
30.9%
174,661
Compared to previous year
1
1
Persist and rehydrate your Pinia state between page reloads.
This project use SemVer for versioning. For the versions available, see the tags on this repository.
1# npm 2npm i pinia-plugin-persistedstate-2
1<script src="https://unpkg.com/pinia-plugin-persistedstate-2"></script>
You can find the library on window.PiniaPluginPersistedstate_2
.
All you need to do is add the plugin to pinia:
1import { createPinia } from 'pinia' 2import { createPersistedStatePlugin } from 'pinia-plugin-persistedstate-2' 3 4const pinia = createPinia() 5const installPersistedStatePlugin = createPersistedStatePlugin() 6pinia.use((context) => installPersistedStatePlugin(context))
The default storage is localStorage
, but you can also use other storage, e.g., using localForage:
1// ... 2import localforage from 'localforage' 3 4// ... 5pinia.use( 6 createPersistedStatePlugin({ 7 storage: { 8 getItem: async (key) => { 9 return localforage.getItem(key) 10 }, 11 setItem: async (key, value) => { 12 return localforage.setItem(key, value) 13 }, 14 removeItem: async (key) => { 15 return localforage.removeItem(key) 16 }, 17 }, 18 }), 19)
Serialization and deserialization allow you to customize the state that gets persisted and rehydrated.
For example, if your state has circular references, you may need to use json-stringify-safe to prevent circular references from being thrown:
1// ... 2import stringify from 'json-stringify-safe' 3 4// ... 5pinia.use( 6 createPersistedStatePlugin({ 7 serialize: (value) => stringify(value), 8 }), 9)
During updates, we may change structure of stores due to refactoring or other reasons.
To support this feature, this plugin provides the migrate
function, which will be called after deserialize
but before actually overwriting/patching the store:
1// ... 2const store = defineStore( 3 'store', 4 () => { 5 return { 6 // oldKey: ref(0), 7 newKey: ref(0), 8 } 9 }, 10 { 11 persistedState: { 12 overwrite: true, 13 migrate: (state) => { 14 if (typeof state.oldKey === 'number') { 15 return { 16 newKey: state.oldKey, 17 } 18 } 19 20 return state 21 }, 22 }, 23 }, 24)()
Follow Pinia - Nuxt.js installation steps.
1// nuxt.config.js 2export default { 3 // ... other options 4 buildModules: [ 5 // Nuxt 2 only: 6 // https://composition-api.nuxtjs.org/getting-started/setup#quick-start 7 '@nuxtjs/composition-api/module', 8 '@pinia/nuxt', 9 ], 10}
Create the plugin below to plugins config in your nuxt.config.js file.
1// nuxt.config.js 2export default { 3 // ... other options 4 plugins: ['@/plugins/persistedstate.js'], 5}
1// plugins/persistedstate.js 2import { createPersistedStatePlugin } from 'pinia-plugin-persistedstate-2' 3 4export default function ({ $pinia }) { 5 if (process.client) { 6 $pinia.use(createPersistedStatePlugin()) 7 } 8}
1// plugins/persistedstate.js 2import { createPersistedStatePlugin } from 'pinia-plugin-persistedstate-2' 3import Cookies from 'js-cookie' 4import cookie from 'cookie' 5 6export default function ({ $pinia, ssrContext }) { 7 $pinia.use( 8 createPersistedStatePlugin({ 9 storage: { 10 getItem: (key) => { 11 // See https://nuxtjs.org/guide/plugins/#using-process-flags 12 if (process.server) { 13 const parsedCookies = cookie.parse(ssrContext.req.headers.cookie) 14 return parsedCookies[key] 15 } else { 16 return Cookies.get(key) 17 } 18 }, 19 // Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON. 20 setItem: (key, value) => 21 Cookies.set(key, value, { expires: 365, secure: false }), 22 removeItem: (key) => Cookies.remove(key), 23 }, 24 }), 25 ) 26}
For more details, see type.ts.
persist?: boolean
: Defaults to true
. Whether to persist store.
storage?: IStorage
: Defaults to localStorage
. Where to store persisted state.
assertStorage?: (storage: IStorage) => void | never
: Perform a Write-Delete operation by default. To ensure storage
is available.
overwrite?: boolean
: Defaults to false
. Whether to overwrite initial state when rehydrating. When this flat is true use store.$state = persistedState
, store.$patch(persistedState)
otherwise.
merge?: (state: S, savedState: S) => S
: Defaults to (state, savedState) => savedState
. A function for merging state when rehydrating state.
serialize?: (state: S): any
: Defaults to JSON.stringify
. This method will be called right before storage.setItem
.
deserialize?: (value: any): any
: Defaults to JSON.parse
. This method will be called right after storage.getItem
.
filter?: (mutation, state): boolean
: A function that will be called to filter any mutations which will trigger setState on storage eventually.
getItem: (key: string) => any | Promise<any>
: Any value other than undefined
or null
will be rehydrated.
setItem: (key: string, value: any) => void | Promise<void>
removeItem: (key: string) => void | Promise<void>
Supports all common options. These options are the default values for each store, you can set the most commonly used options in the plugin options, and override/extend it in the store options.
1createPersistedStatePlugin({
2 // plugin options goes here
3})
Supports all common options.
1defineStore( 2 'counter-store', 3 () => { 4 const currentValue = ref(0) 5 const increment = () => currentValue.value++ 6 7 return { 8 currentValue, 9 increment, 10 } 11 }, 12 { 13 persistedState: { 14 // store options goes here 15 }, 16 }, 17)
key?: string
: Defaults to store.$id
. The key to store the persisted state under.
includePaths?: (string | string[])[]
: An array of any paths to partially persist the state. Use dot-notation ['key', 'nested.key', ['special.key']]
for nested fields.
excludePaths?: (string | string[])[]
: Opposite to includePaths
, An array of any paths to exclude. Due to deep copying, excludePaths
may cause performance issues, if possible, please use includePaths
instead.
migrate?: (value: any) => any | Promise<any>
: The migrate
function enables versioning store. This will be called after deserialize
but before actually overwriting/patching the store.
beforeHydrate?: (oldState: S) => void
: This function gives you the opportunity to perform some tasks before actually overwriting/patching the store, such as cleaning up the old state.
store.$persistedState.isReady: () => Promise<void>
: Whether store is hydrated
store.$persistedState.pending: boolean
: Whether store is persisting
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
This project is licensed under the MIT License - see the LICENSE file for details
No vulnerabilities found.
No security vulnerabilities found.