### Enable Persistence in Pinia Stores (Setup Syntax) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/index_display=source This TypeScript example shows how to enable persistence for a Pinia store using the setup syntax. By setting `persist: true` in the store options, the store's state will be automatically persisted. ```ts import { defineStore } from 'pinia' import { ref } from 'vue' export const useStore = defineStore( 'main', () => { const someState = ref('hello pinia') return { someState } }, { persist: true, }, ) ``` -------------------------------- ### Install pinia-plugin-persistedstate with Package Managers Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/index_display=source These commands show how to install the pinia-plugin-persistedstate using popular package managers like pnpm, npm, and yarn. Ensure you have Pinia installed before proceeding. ```sh pnpm add pinia-plugin-persistedstate ``` ```sh npm i pinia-plugin-persistedstate ``` ```sh yarn add pinia-plugin-persistedstate ``` -------------------------------- ### Configure store persistence options Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/praz/pinia-plugin-persistedstate This example demonstrates how to configure persistence for a Pinia store with custom options. It uses an object for the `persist` property to specify configurations like `storage` and `pick`. This allows fine-grained control over which parts of the state are persisted and where they are stored. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', () => { const someState = ref('hello pinia') return { someState } }, { persist: { storage: sessionStorage, pick: ['someState'], }, }) ``` -------------------------------- ### Configure Pinia Store Persistence (TypeScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source Demonstrates how to configure state persistence for a Pinia store using both setup and options syntaxes in TypeScript. The 'persist' property accepts a configuration object for customization. ```typescript import { defineStore } from 'pinia' import { ref } from 'vue' export const useStore = defineStore('main', () => { const someState = ref('hello pinia') return { someState } }, { persist: { // CONFIG OPTIONS HERE } }) ``` ```typescript import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => ({ someState: 'hello pinia', }), persist: { // CONFIG OPTIONS HERE }, }) ``` -------------------------------- ### Persisting Pinia Stores with VueUse useLocalStorage Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/why_display=source An example demonstrating how to persist Pinia store data using VueUse's useLocalStorage. This approach does not require injecting a Pinia plugin. It utilizes the useLocalStorage composable to synchronize store state with localStorage. ```typescript import { useLocalStorage } from '@vueuse/core' import { defineStore } from 'pinia' defineStore('store', () => { const someState = useLocalStorage('stored-state', 'initialValue') return { someState } }) ``` -------------------------------- ### Enable Persistence in Pinia Stores (Option Syntax) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/index_display=source This TypeScript example illustrates how to enable persistence for a Pinia store using the option syntax. Setting `persist: true` within the store definition will ensure the store's state is saved. ```ts import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => { return { someState: 'hello pinia', } }, persist: true, }) ``` -------------------------------- ### Initialize Plugin with Global Key Option (TypeScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced_display=source Initializes the pinia-plugin-persistedstate with a global key option, defining a custom naming convention for persisted store keys. This example prefixes store keys with '__persisted__'. It requires 'pinia' and 'pinia-plugin-persistedstate'. ```typescript import { createPinia } from 'pinia' import { createPersistedState } from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(createPersistedState({ key: id => `__persisted__${id}`, })) ``` -------------------------------- ### TypeScript: Persisting Returned Refs in Setup Stores Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/limitations_display=source Demonstrates how only returned refs from setup stores are persisted by pinia-plugin-persistedstate. Computed properties, whether returned or not, are not persisted. This is due to Pinia's internal handling of setup store declarations where refs become state and computed properties become getters. ```typescript const useMyStore = defineStore('myStore', () => { const count = ref(0); const name = ref('Praz'); const doubleCount = computed(() => count.value * 2); function increment() { count.value++; } return { count, name, increment }; }); ``` -------------------------------- ### Trigger Manual Hydration for a Store (TypeScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced_display=source Demonstrates how to manually trigger the hydration process for a Pinia store using the `$hydrate` method. This example shows the basic usage without options. Requires 'pinia'. ```typescript import { defineStore } from 'pinia' // Assuming 'store' is an existing store instance // For example: const store = useMyStore(); // store.$hydrate() ``` -------------------------------- ### Execute Code Before State Hydration Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source This example demonstrates the use of the 'beforeHydrate' hook, which runs a function immediately before the store's state is hydrated with persisted data. This hook receives a `PiniaPluginContext` object, allowing access to the store and other context information, useful for pre-hydration logic or validation. ```typescript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { beforeHydrate: (ctx) => { console.log(`about to hydrate '${ctx.store.$id}'`) } }, }) ``` -------------------------------- ### Custom Serializer with Zipson for Pinia State Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config Implements a custom serializer for Pinia state persistence using `zipson` for compression. This example demonstrates how to integrate third-party libraries for serialization/deserialization. ```javascript import { defineStore } from 'pinia' import { parse, stringify } from 'zipson' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { serializer: { deserialize: parse, serialize: stringify } }, }) ``` -------------------------------- ### Persist Specific State with Pick Option Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source This example demonstrates how to use the 'pick' option to selectively persist specific parts of the store's state. The 'pick' option takes an array of dot-notation paths to the state properties that should be persisted. If 'pick' is undefined, the entire state is persisted. If 'pick' is an empty array, no state is persisted. ```typescript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ save: { me: 'saved', notMe: 'not-saved', }, saveMeToo: 'saved', }), persist: { pick: ['save.me', 'saveMeToo'], }, }) ``` -------------------------------- ### Execute Code After State Hydration Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source This example illustrates the 'afterHydrate' hook, which executes a function after the store's state has been successfully hydrated with persisted data. The hook is provided with the `PiniaPluginContext`, enabling post-hydration actions such as logging, data normalization, or triggering subsequent operations. ```typescript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { afterHydrate: (ctx) => { console.log(`just hydrated '${ctx.store.$id}'`) } }, }) ``` -------------------------------- ### Reference Loss Example in Pinia Plugin Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/limitations Demonstrates how object references are lost after serialization and deserialization with pinia-plugin-persistedstate. Initially, two variables point to the same object, but after hydration, they point to separate objects with identical content, breaking reactivity. ```javascript const a = { 1: 'one', 2: 'two', // ... } const b = a // Before serialization, a and b point to the same object: a === b // -> true // After deserialization, a and b are two different objects with the same content: a === b // -> false ``` -------------------------------- ### Handle Hydration Errors Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source This example showcases the 'onHydrateError' hook, designed to catch and handle any errors that occur during the state hydration process. It provides access to the thrown `Error` object and the `store` instance, allowing for custom error management, logging, or conditional re-throwing of the error. ```typescript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { onHydrateError: (error, store) => { console.log(`on hydrate error`) console.log(error) // handle error } }, }) ``` -------------------------------- ### Exclude State from Persistence with Omit Option Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source This example shows how to use the 'omit' option to exclude specific parts of the store's state from being persisted. The 'omit' option accepts an array of dot-notation paths to the state properties that should not be persisted. If 'omit' is undefined or an empty array, the entire state is persisted. ```typescript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ ignore: { me: 'not-saved', notMe: 'saved', }, ignoreMeToo: 'not-saved', }), persist: { omit: ['ignore.me', 'ignoreMeToo'], }, }) ``` -------------------------------- ### Set Global Key for Store Persistence Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced Configures a global key generation strategy for all persisted stores. The `key` option accepts a function that receives the store's ID and returns a custom string key. This overrides the default behavior of using the store's ID as the key. Example shows prefixing store keys with '__persisted__'. ```javascript import { createPinia } from 'pinia' import { createPersistedState } from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(createPersistedState({ key: id => `__persisted__${id}`, })) ``` ```javascript import { defineStore } from 'pinia' defineStore('store', { state: () => ({ saved: '' }), persist: true, }) ``` -------------------------------- ### Add pinia-plugin-persistedstate to Pinia Instance Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/index This code demonstrates how to integrate the pinia-plugin-persistedstate into your Pinia instance. After creating a Pinia instance, you apply the plugin using the `pinia.use()` method. This enables the persistence features for your stores. ```javascript import { createPinia } from 'pinia' import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(piniaPluginPersistedstate) ``` -------------------------------- ### Define Pinia Store with Persistence Options (Composition API) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config Demonstrates how to define a Pinia store using the Composition API and enable persistence with configurable options. This approach allows for flexible state management and persistence. ```javascript import { defineStore } from 'pinia' import { ref } from 'vue' export const useStore = defineStore('main', () => { const someState = ref('hello pinia') return { someState } }, { persist: { // CONFIG OPTIONS HERE } }) ``` -------------------------------- ### Implement Custom Serializer with Zipson (TypeScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source Demonstrates how to use a custom serializer for persisting and rehydrating store state, utilizing the 'zipson' library for more efficient serialization. This involves providing 'serialize' and 'deserialize' functions in the 'serializer' option. ```typescript import { defineStore } from 'pinia' import { parse, stringify } from 'zipson' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { serializer: { deserialize: parse, serialize: stringify } }, }) ``` -------------------------------- ### Enable store persistence Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/praz/pinia-plugin-persistedstate This code shows how to enable persistence for a specific Pinia store by adding the `persist: true` option within the store definition. This will apply the default persistence configuration to the store. Any state defined in this store will be automatically persisted. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: true, }) ``` -------------------------------- ### Persist Pinia Store using VueUse useLocalStorage Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/why This snippet demonstrates how to persist Pinia store data using VueUse's `useLocalStorage` hook. This is presented as an alternative to injecting a Pinia plugin for store persistence. It requires the `@vueuse/core` package. ```javascript import { useLocalStorage } from '@vueuse/core' import { defineStore } from 'pinia' defineStore('store', () => { const someState = useLocalStorage('stored-state', 'initialValue') return { someState } }) ``` -------------------------------- ### Pinia Persisted State Plugin Configuration Options Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source This section details the configuration options available for the Pinia persisted state plugin, including pick, omit, beforeHydrate, afterHydrate, and onHydrateError. ```APIDOC ## Persisted State Configuration Options This plugin utilizes `zipson`'s `stringify`/`parse` for serialization/deserialization with compression. ### `pick` - **type**: `string[] | Path[]` - **default**: `undefined` Array of dot-notation paths to pick what should be persisted. `[]` means no state is persisted and `undefined` means the whole state is persisted. :::details Example ```ts import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ save: { me: 'saved', notMe: 'not-saved', }, saveMeToo: 'saved', }), persist: { pick: ['save.me', 'saveMeToo'], }, }) ``` In this store, only `save.me` and `saveMeToo` values will be persisted. `save.notMe` will not be persisted. ::: > [!TIP] > Auto-completion from state-infered type can help you with what paths can be picked. ### `omit` - **type**: `string[] | Path[]` - **default**: `undefined` Array of dot-notation paths to omit from what should be persisted. `[]` or `undefined` means the whole state persisted (nothing is omitted). :::details Example ```ts import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ ignore: { me: 'not-saved', notMe: 'saved', }, ignoreMeToo: 'not-saved', }), persist: { omit: ['ignore.me', 'ignoreMeToo'], }, }) ``` In this store, only `ignore.notMe` value will be persisted. `ignore.me` and `ignoreMeToo` will not be persisted. ::: > [!TIP] > Auto-completion from state-infered type can help you with what paths can be omitted. ### `beforeHydrate` - **type**: `(context: PiniaPluginContext) => void` - **default**: `undefined` Hook function run before hydrating a store state with persisted data. The hook gives access to the whole [`PiniaPluginContext`](https://pinia.vuejs.org/api/pinia/interfaces/PiniaPluginContext.html). This can be used to enforce specific actions before hydration. :::details Example ```ts import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { beforeHydrate: (ctx) => { console.log(`about to hydrate '${ctx.store.$id}'`) } }, }) ``` This store will log `about to hydrate 'store'` _before_ being rehydrated. ::: > [!WARNING] > Beware of interacting with `PiniaPluginContext`, unexpected behaviors may occur. ### `afterHydrate` - **type**: `(context: PiniaPluginContext) => void` - **default**: `undefined` Hook function run after rehydrating a persisted state. The hook gives access to the whole [`PiniaPluginContext`](https://pinia.vuejs.org/api/interfaces/pinia.PiniaPluginContext.html). This can be used to enforce specific actions after hydration. :::details Example ```ts import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { afterHydrate: (ctx) => { console.log(`just hydrated '${ctx.store.$id}'`) } }, }) ``` This store will log `just hydrated 'store'` _after_ being rehydrated. ::: > [!WARNING] > Beware of interacting with `PiniaPluginContext`, unexpected behaviors may occur. ### `onHydrateError` - **type**: `(error: Error, store: Store) => void` - **default**: `undefined` Hook function run after an error occurred during hydration. The hook gives access to the thrown `error` object and the `store` object. This can be used to handle error encountered during hydration or rethrow the error for it to bubble up. :::details Example ```ts import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { onHydrateError: (error, store) => { console.log(`on hydrate error`) console.log(error) // handle error } }, }) ``` ``` -------------------------------- ### Define Pinia Store with Persistence Options (Options API) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config Illustrates defining a Pinia store using the Options API and configuring persistence. This method is suitable for projects that prefer the Options API structure for Pinia stores. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => ({ someState: 'hello pinia', }), persist: { // CONFIG OPTIONS HERE }, }) ``` -------------------------------- ### Initialize Plugin with Global Persistence Options Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced Initializes the pinia-plugin-persistedstate with global options for all stores. This sets default storage, serializer, and debug configurations. Any store-specific `persist` options will override these global defaults. It's recommended to use `createPersistedState` for global configuration instead of the default export. ```javascript import { createPinia } from 'pinia' import { createPersistedState } from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(createPersistedState({ storage: sessionStorage, })) ``` -------------------------------- ### Use sessionStorage for Persistence (TypeScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source Shows how to configure the plugin to use sessionStorage instead of the default localStorage for persisting store state. This is achieved by specifying the 'storage' option within the 'persist' configuration. ```typescript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { storage: sessionStorage, }, }) ``` -------------------------------- ### Integrate pinia-plugin-persistedstate with Pinia Instance Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/index_display=source This TypeScript code demonstrates how to add the pinia-plugin-persistedstate to your Pinia instance. This step is crucial for enabling the persistence features across your stores. ```ts import { createPinia } from 'pinia' import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(piniaPluginPersistedstate) ``` -------------------------------- ### Set Custom Storage Key for Persistence (TypeScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config_display=source Illustrates how to define a custom key for storing persistent state in localStorage using the 'key' option within the 'persist' configuration. This allows for unique identification of stored data. ```typescript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { key: 'my-custom-key', }, }) ``` -------------------------------- ### Execute Code Before Hydrating Pinia Store State (JavaScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `beforeHydrate` hook function runs before a store's state is hydrated with persisted data. It provides access to the `PiniaPluginContext`, allowing for pre-hydration actions. Use with caution as interacting with the context can lead to unexpected behavior. ```javascript import { defineStore } from 'pinia'; export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { beforeHydrate: (ctx) => { console.log(`about to hydrate '${ctx.store.$id}'`); } }, }); ``` -------------------------------- ### beforeHydrate Hook Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `beforeHydrate` hook function is executed before hydrating a store's state with persisted data. It provides access to the `PiniaPluginContext`, allowing for pre-hydration actions. ```APIDOC ## beforeHydrate Hook ### Description Hook function run before hydrating a store state with persisted data. The hook gives access to the whole `PiniaPluginContext`. This can be used to enforce specific actions before hydration. ### Type `(context: PiniaPluginContext) => void` ### Default `undefined` ### Example ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { beforeHydrate: (ctx) => { console.log(`about to hydrate '${ctx.store.$id}'`) } }, }) ``` ### Warning Beware of interacting with `PiniaPluginContext`, unexpected behaviors may occur. ``` -------------------------------- ### Enable State Persistence in Pinia Stores Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/index This snippet illustrates how to enable state persistence for Pinia stores by setting the `persist` option to `true` when defining the store. This applies default persistence settings to the entire store. Two common ways of defining Pinia stores (Options API and Composition API) are shown. ```javascript import { defineStore } from 'pinia' import { ref } from 'vue' export const useStore = defineStore( 'main', () => { const someState = ref('hello pinia') return { someState } }, { persist: true, }, ) ``` ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => { return { someState: 'hello pinia', } }, persist: true, }) ``` -------------------------------- ### Add pinia-plugin-persistedstate Nuxt module Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/praz/pinia-plugin-persistedstate This snippet shows how to integrate pinia-plugin-persistedstate into a Nuxt.js application. It requires adding both the core '@pinia/nuxt' module and 'pinia-plugin-persistedstate/nuxt' to the `modules` array in your `nuxt.config.ts` file. This enables SSR support out-of-the-box. ```typescript export default defineNuxtConfig({ modules: [ '@pinia/nuxt', // required 'pinia-plugin-persistedstate/nuxt', ], }) ``` -------------------------------- ### Manually Hydrate Pinia Store State with $hydrate Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced_display=source Allows manual fetching and application of store state from configured storages. The `$hydrate` method replaces the current state with data from storage. It accepts an options object, where `runHooks` can be set to `false` to prevent hooks from being triggered. Use with caution, as manual hydration is rarely needed. ```typescript import { defineStore } from 'pinia' const useStore = defineStore('store', { state: () => ({ someData: 'Hello Pinia' }) }) const store = useStore() store.$hydrate({ runHooks: false }) ``` -------------------------------- ### Debug Option Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `debug` option, when set to true, enables logging of any errors that occur during the persistence or hydration of stores using `console.error`. ```APIDOC ## Debug Option ### Description When set to true, any error that may occur while persisting/hydrating stores will be logged with `console.error`. ### Type `boolean` ### Default `false` ### Warning No environment check is done: if this is enabled, errors will also be logged in production. ``` -------------------------------- ### Persisting Specific State Properties with 'pick' Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config Configures the plugin to only persist specified state properties using dot-notation paths. This allows fine-grained control over what data is saved. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ save: { me: 'saved', notMe: 'not-saved', }, saveMeToo: 'saved', }), persist: { pick: ['save.me', 'saveMeToo'], }, }) ``` -------------------------------- ### Configure Multiple Persistence Targets per Store Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced Allows a single store to persist its state to multiple storage locations simultaneously. The `persist` option can be an array of configuration objects, each specifying its own `pick` (or `paths`) and `storage`. Data inconsistency can occur if not careful with overlapping paths or missing `paths`. ```javascript import { defineStore } from 'pinia' defineStore('store', { state: () => ({ toLocal: '', toSession: '', toNowhere: '', }), persist: [ { pick: ['toLocal'], storage: localStorage, }, { pick: ['toSession'], storage: sessionStorage, }, ], }) ``` -------------------------------- ### Configure Global Key Prefix/Postfix for Pinia Persisted State Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/frameworks/nuxt Defines a global template for keys used in Pinia persisted state. The `%id` token will be replaced by the store's ID, allowing for structured key naming. ```javascript export default defineNuxtConfig({ modules: [ '@pinia/nuxt', 'pinia-plugin-persistedstate/nuxt' ], piniaPluginPersistedstate: { key: 'prefix_%id_postfix', }, }) ``` -------------------------------- ### Define Store with Custom Global Key (TypeScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced_display=source Defines a Pinia store that will utilize the custom global key defined during plugin initialization. The 'persist: true' option ensures the store's state is persisted. Requires 'pinia'. ```typescript import { defineStore } from 'pinia' defineStore('store', { state: () => ({ saved: '' }), persist: true, }) ``` -------------------------------- ### Using Session Storage for Pinia State Persistence Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config Sets up `sessionStorage` as the storage mechanism for persisting Pinia store state. This is useful for temporary data that should only persist for the duration of a user's session. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { storage: sessionStorage, }, }) ``` -------------------------------- ### Handle Conflicting Persistence Configurations Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced Demonstrates a scenario where a store is configured to persist to multiple storage locations without specifying distinct paths. In such cases, during hydration, the state from the latter declared storage (e.g., `sessionStorage`) will overwrite state from earlier declared storages (e.g., `localStorage`), potentially leading to data loss or inconsistency. ```javascript import { defineStore } from 'pinia' defineStore('store', { state: () => ({ someData: 'Hello Pinia' }), persist: [ { storage: localStorage, }, { storage: sessionStorage, }, ], }) ``` -------------------------------- ### Configure Pinia Store with Cookies and maxAge - TypeScript Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/frameworks/nuxt_display=source Demonstrates configuring a Pinia store to use cookies for persistence, specifically addressing a limitation with Cloudflare workers. It uses 'maxAge' instead of 'expires' for cookie duration, with a duration of one year. ```typescript import { defineStore } from 'pinia' import { ref } from 'vue' export const useStore = defineStore( 'main', () => { const someState = ref('hello pinia') return { someState } }, { persist: piniaPluginPersistedstate.cookies({ maxAge: 365 * 24 * 60 * 60, }), }, ) ``` -------------------------------- ### Manually Persist Pinia Store State with $persist Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced This snippet demonstrates how to manually trigger the persistence of a Pinia store's state to configured storage using the `$persist` method. It requires importing `defineStore` from Pinia and defining a store. The `$persist` method is then called on an instance of the store. ```javascript import { defineStore } from 'pinia' const useStore = defineStore('store', { state: () => ({ someData: 'Hello Pinia' }) }) const store = useStore() store.$persist() ``` -------------------------------- ### Execute Code After Hydrating Pinia Store State (JavaScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `afterHydrate` hook function executes after a store's persisted state has been rehydrated. It receives the `PiniaPluginContext`, enabling post-hydration actions. Developers should be mindful of potential unexpected behaviors when interacting with the context. ```javascript import { defineStore } from 'pinia'; export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { afterHydrate: (ctx) => { console.log(`just hydrated '${ctx.store.$id}'`); } }, }); ``` -------------------------------- ### Custom Storage Key for Pinia State Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config Configures a custom key for storing and retrieving Pinia state in local storage. This allows for distinct storage keys per store, preventing potential conflicts. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { key: 'my-custom-key', }, }) ``` -------------------------------- ### Manually Trigger Store Hydration Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/advanced Provides a method to manually trigger the hydration of a store's state from its configured storage. The `$hydrate` method can be called on a store instance. By default, it also triggers `beforeHydrate` and `afterHydrate` hooks, but this behavior can be suppressed by passing `{ runHooks: false }`. ```javascript import { defineStore } from 'pinia' const useStore = defineStore('store', { state: () => ({ someData: 'Hello Pinia' }) }) // Usage: const store = useStore() store.$hydrate({ runHooks: false }) ``` -------------------------------- ### Configure Pinia Persisted State to Use Local Storage Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/frameworks/nuxt Sets up the Pinia persisted state plugin to utilize localStorage for storing state. This configuration is applied within the store's `persist` object. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => { return { someState: 'hello pinia', } }, persist: { storage: piniaPluginPersistedstate.localStorage(), }, }) ``` -------------------------------- ### afterHydrate Hook Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `afterHydrate` hook function is executed after rehydrating a persisted state. It provides access to the `PiniaPluginContext`, allowing for post-hydration actions. ```APIDOC ## afterHydrate Hook ### Description Hook function run after rehydrating a persisted state. The hook gives access to the whole `PiniaPluginContext`. This can be used to enforce specific actions after hydration. ### Type `(context: PiniaPluginContext) => void` ### Default `undefined` ### Example ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { afterHydrate: (ctx) => { console.log(`just hydrated '${ctx.store.$id}'`) } }, }) ``` ### Warning Beware of interacting with `PiniaPluginContext`, unexpected behaviors may occur. ``` -------------------------------- ### Using Max-Age Instead of Expires with Cookies on Cloudflare Workers Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/frameworks/nuxt This snippet demonstrates how to configure cookie persistence with pinia-plugin-persistedstate for use in Cloudflare workers. It highlights the limitation of using JavaScript Date objects directly in the worker's global context and provides a workaround by using 'maxAge' for expiration, which is compatible with Cloudflare environments. The code shows the recommended approach using 'maxAge' and comments out the problematic 'expires' usage. ```javascript import { defineStore } from 'pinia' import { ref } from 'vue' export const useStore = defineStore( 'main', () => { const someState = ref('hello pinia') return { someState } }, { persist: piniaPluginPersistedstate.cookies({ // DO NOT USE - the date in cloudflare worker will return 1970-01-01 // [!code --] expires: new Date(new Date().setFullYear(new Date().getFullYear() + 1)), // [!code --] // USE THIS INSTEAD // [!code ++] maxAge: 365 * 24 * 60 * 60, // [!code ++] }), }, ) ``` -------------------------------- ### Omitting Specific State Properties from Persistence with 'omit' Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config Sets up the plugin to exclude specified state properties from being persisted using dot-notation paths. This is useful for sensitive or temporary data that should not be saved. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ ignore: { me: 'not-saved', notMe: 'saved', }, ignoreMeToo: 'not-saved', }), persist: { omit: ['ignore.me', 'ignoreMeToo'], }, }) ``` -------------------------------- ### Configure Global Pinia Persisted State Options in Nuxt Config Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/frameworks/nuxt Sets global configurations for pinia-plugin-persistedstate within the Nuxt config file. This includes specifying the default storage, cookie options, and enabling debug mode. ```javascript export default defineNuxtConfig({ modules: [ '@pinia/nuxt', 'pinia-plugin-persistedstate/nuxt' ], piniaPluginPersistedstate: { storage: 'cookies', cookieOptions: { sameSite: 'lax', }, debug: true, }, }) ``` -------------------------------- ### onPersistError Hook Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `onPersistError` hook function is executed when an error occurs during the persistence process. It provides access to the error object and the store object, allowing for custom error handling. ```APIDOC ## onPersistError Hook ### Description Hook function run after an error occurred during persistence. The hook gives access to the thrown `error` object and the `store` object. This can be used to handle error encountered during persistence or rethrow the error for it to bubble up. ### Type `(error: Error, store: Store) => void` ### Default `undefined` ### Example ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { onPersistError: (error, store) => { console.log(`on persist error`) console.log(error) // handle error } }, }) ``` ``` -------------------------------- ### Handle Errors During Pinia Store Persistence (JavaScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `onPersistError` hook function is called subsequent to an error arising during the persistence of a store's state. It supplies the `error` object and the `store` object, facilitating error management or re-throwing for error propagation. This ensures data integrity and informs about persistence failures. ```javascript import { defineStore } from 'pinia'; export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { onPersistError: (error, store) => { console.log(`on persist error`); console.log(error); // handle error } }, }); ``` -------------------------------- ### Add Pinia Persisted State Nuxt Module to Nuxt Config Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/frameworks/nuxt Configures the Nuxt application to use the Pinia store and the pinia-plugin-persistedstate module. This is done within the nuxt.config.ts file. ```javascript export default defineNuxtConfig({ modules: [ '@pinia/nuxt', 'pinia-plugin-persistedstate/nuxt', ], }) ``` -------------------------------- ### onHydrateError Hook Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `onHydrateError` hook function is executed when an error occurs during the hydration process. It provides access to the error object and the store object, enabling custom error handling. ```APIDOC ## onHydrateError Hook ### Description Hook function run after an error occurred during hydration. The hook gives access to the thrown `error` object and the `store` object. This can be used to handle error encountered during hydration or rethrow the error for it to bubble up. ### Type `(error: Error, store: Store) => void` ### Default `undefined` ### Example ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { onHydrateError: (error, store) => { console.log(`on hydrate error`) console.log(error) // handle error } }, }) ``` ``` -------------------------------- ### Handle Errors During Pinia Store Hydration (JavaScript) Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/config The `onHydrateError` hook is invoked when an error occurs during the store's hydration process. It provides the `error` object and the `store` object, allowing for error handling or re-throwing to propagate the error. This hook is crucial for robust state management. ```javascript import { defineStore } from 'pinia'; export const useStore = defineStore('store', { state: () => ({ someState: 'hello pinia', }), persist: { onHydrateError: (error, store) => { console.log(`on hydrate error`); console.log(error); // handle error } }, }); ``` -------------------------------- ### Configure Pinia Persisted State to Use Session Storage Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/frameworks/nuxt Configures the Pinia persisted state plugin to use sessionStorage for state persistence. The `storage` option is set to `piniaPluginPersistedstate.sessionStorage()` in the store's `persist` configuration. ```javascript import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => { return { someState: 'hello pinia', } }, persist: { storage: piniaPluginPersistedstate.sessionStorage(), }, }) ``` -------------------------------- ### TypeScript: Handling Lost References After Deserialization Source: https://codeberg.org/praz/pinia-plugin-persistedstate/src/branch/main/docs/guide/limitations_display=source Illustrates how references to objects are lost after serialization and deserialization with pinia-plugin-persistedstate. Initially, two variables 'a' and 'b' point to the same object. After persistence, they become distinct objects with identical content, losing their shared reference and reactivity. ```typescript const a = { 1: 'one', 2: 'two', // ... }; const b = a; a === b // -> true // After deserialization: a === b // -> false ```