npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pinia-plugin-persistedstate-2

v2.0.26

Published

Persist and rehydrate your Pinia state between page reloads

Downloads

14,587

Readme

pinia-plugin-persistedstate-2

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.

CI NPM version

✨ Features

  • 🎨 Configurable globally and in every store.
  • 💪 Type Safe
  • 📦 Extremely small

🚀 Getting Started

Installation

Package Manager

# npm
npm i pinia-plugin-persistedstate-2

CDN

<script src="https://unpkg.com/pinia-plugin-persistedstate-2"></script>

You can find the library on window.PiniaPluginPersistedstate_2.

Usage

All you need to do is add the plugin to pinia:

import { createPinia } from 'pinia'
import { createPersistedStatePlugin } from 'pinia-plugin-persistedstate-2'

const pinia = createPinia()
const installPersistedStatePlugin = createPersistedStatePlugin()
pinia.use((context) => installPersistedStatePlugin(context))

Storage

The default storage is localStorage, but you can also use other storage, e.g., using localForage:

// ...
import localforage from 'localforage'

// ...
pinia.use(
  createPersistedStatePlugin({
    storage: {
      getItem: async (key) => {
        return localforage.getItem(key)
      },
      setItem: async (key, value) => {
        return localforage.setItem(key, value)
      },
      removeItem: async (key) => {
        return localforage.removeItem(key)
      },
    },
  }),
)

Serialization and Deserialization

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:

// ...
import stringify from 'json-stringify-safe'

// ...
pinia.use(
  createPersistedStatePlugin({
    serialize: (value) => stringify(value),
  }),
)

Migrations

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:

// ...
const store = defineStore(
  'store',
  () => {
    return {
      // oldKey: ref(0),
      newKey: ref(0),
    }
  },
  {
    persistedState: {
      overwrite: true,
      migrate: (state) => {
        if (typeof state.oldKey === 'number') {
          return {
            newKey: state.oldKey,
          }
        }

        return state
      },
    },
  },
)()

SSR

Nuxt.js

Follow Pinia - Nuxt.js installation steps.

// nuxt.config.js
export default {
  // ... other options
  buildModules: [
    // Nuxt 2 only:
    // https://composition-api.nuxtjs.org/getting-started/setup#quick-start
    '@nuxtjs/composition-api/module',
    '@pinia/nuxt',
  ],
}
With localStorage (client-only) (nuxt@2 example)

Create the plugin below to plugins config in your nuxt.config.js file.

// nuxt.config.js
export default {
  // ... other options
  plugins: ['@/plugins/persistedstate.js'],
}
// plugins/persistedstate.js
import { createPersistedStatePlugin } from 'pinia-plugin-persistedstate-2'

export default function ({ $pinia }) {
  if (process.client) {
    $pinia.use(createPersistedStatePlugin())
  }
}
With cookies (universal) (nuxt@3 example)
// plugins/persistedstate.js
import { createPersistedStatePlugin } from 'pinia-plugin-persistedstate-2'
import Cookies from 'js-cookie'
import cookie from 'cookie'

export default function ({ $pinia, ssrContext }) {
  $pinia.use(
    createPersistedStatePlugin({
      storage: {
        getItem: (key) => {
          // See https://nuxtjs.org/guide/plugins/#using-process-flags
          if (process.server) {
            const parsedCookies = cookie.parse(ssrContext.req.headers.cookie)
            return parsedCookies[key]
          } else {
            return Cookies.get(key)
          }
        },
        // Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
        setItem: (key, value) =>
          Cookies.set(key, value, { expires: 365, secure: false }),
        removeItem: (key) => Cookies.remove(key),
      },
    }),
  )
}

📖 API

For more details, see type.ts.

Common Options

  • 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.

IStorage

  • 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>

Plugin Options

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.

createPersistedStatePlugin({
  // plugin options goes here
})

Store Options

Supports all common options.

defineStore(
  'counter-store',
  () => {
    const currentValue = ref(0)
    const increment = () => currentValue.value++

    return {
      currentValue,
      increment,
    }
  },
  {
    persistedState: {
      // store options goes here
    },
  },
)
  • 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 Properties

  • store.$persistedState.isReady: () => Promise<void>: Whether store is hydrated

  • store.$persistedState.pending: boolean: Whether store is persisting

🤝 Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

📝 License

This project is licensed under the MIT License - see the LICENSE file for details