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-persistence-plugin

v0.0.5

Published

Pinia persistence plugin

Downloads

162

Readme

pinia-persistence-plugin npm (scoped)

Handle Pinia state persistence easily.

Features

  • Support multiple storages.
  • Can be configured globally and in every Pinia store.
  • Support async storages like localForage.
  • Storages, store paths and serialization method can be customized.

Installation

Install with your favorite package manager:

# npm
npm i pinia-persistence-plugin
# yarn
yarn add pinia-persistence-plugin
# pnpm
pnpm add pinia-persistence-plugin

Usage

Add this plugin to your Pinia instance:

import { createPinia } from 'pinia'
import { persistencePlugin } from 'pinia-persistence-plugin'

const pinia = createPinia()
pinia.use(persistencePlugin())

The persistence is enabled by default for all pinia stores and the default storage is localStorage.

Configuration

Plugin Options

persistencePlugin({
 // plugin options goes here
 storeKeysPrefix: 'test',
 persistenceDefault: false,
 storageItemsDefault: [
  {
   storage: sessionStorage,
  },
 ],
 debug: true,
})
  • storeKeysPrefix?: string: Defaults to undefined. Add prefix to stores keys.

  • persistenceDefault?: boolean: Defaults to true. Whether to persist all stores by default.

  • storageItemsDefault?: PluginStorageItem[]: Defaults to localStorage. List of storages.

  • assertStorage?: (storage: Storage) => void | Promise<void>: Perform a write and delete operation by default. To ensure storages is available.

  • ensureAsyncStorageUpdateOrder?: boolean: Ensure that the update of asynchronous storages is done in order

  • debug?: boolean: Defaults to false. Display errors and warnings in console.

PluginStorageItem

  • storage?: Storage: Where to store persisted state

  • includePaths?: string[]: Defaults to []. An array of any paths to partially persist the state

  • excludePaths?: string[]: Defaults to []. An array of any paths to exclude

  • serializer?: Serializer: Object containing serialize and deserialize methods

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

Store Options

defineStore(
 'store',
 () => {
  const count = ref(0)
  const increment = () => count.value++
  return {
   count,
   increment,
  }
 },
 {
  persistence: {
   // store options goes here
   enabled: true,
   storageItems: [
    {
     key: 'sample',
     storage: sessionStorage,
     includePaths: ['count'],
    },
   ],
  },
 }
)
  • enabled?: boolean: Enable persistence for the store
  • storageItems?: StorageItem[]: List of storages.
  • beforeHydrate?: (oldState: S) => void: Perform some tasks before patching the store

StorageItem

  • key?: string: Defaults to store.$id. The persisted store state key. And the same properties as PluginStorageItem

Storage

  • getItem: (key: string) => any | Promise<any>

  • setItem: (key: string, value: any) => void | Promise<void>

  • removeItem: (key: string) => void | Promise<void>

Some examples of use

js-cookie

import { defineStore } from 'pinia'

import Cookies from 'js-cookie'

defineStore('example', {
 // ...
 persistence: {
  enabled: true,
  storageItems: [
   {
    storage: {
     getItem: (key: string) => {
      return Cookies.get(key)
     },
     setItem: (key: string, value: any) => {
      Cookies.set(key, value)
     },
     removeItem: (key: string) => {
      Cookies.remove(key)
     },
    },
   },
  ],
 },
})

localForage

import { defineStore } from 'pinia'

import localforage from 'localforage'

localforage.config({
 driver: [localforage.INDEXEDDB],
 name: 'Test IndexedDB',
 storeName: 'store',
})

defineStore('example', {
 // ...
 persistence: {
  enabled: true,
  storageItems: [
   {
    storage: {
     getItem: async (key: string) => {
      return await localforage.getItem(key)
     },
     setItem: async (key: string, value: any) => {
      await localforage.setItem(key, value)
     },
     removeItem: async (key: string) => {
      await localforage.removeItem(key)
     },
    },
   },
  ],
 },
})

Custom serialize method

import { defineStore } from 'pinia'

import stringify from 'json-stringify-safe'

defineStore('example', {
 // ...
 persistence: {
  enabled: true,
  storageItems: [
   {
    storage: localStorage,
    serializer: {
     serialize: (value: any) => stringify(value),
    },
   },
  ],
 },
})

localStorage with SecureLS encryption

import { defineStore } from 'pinia'

import SecureLS from 'secure-ls'

var ls = new SecureLS({
 encodingType: 'aes',
 isCompression: false,
})

defineStore('example', {
 // ...
 persistence: {
  enabled: true,
  storageItems: [
   {
    key: 'encrypted_data',
    storage: {
     getItem: (key: string) => {
      try {
       return ls.get(key)
      } catch (error) {
       console.error(error)
      }
     },
     setItem: (key: string, value: any) => {
      try {
       ls.set(key, value)
      } catch (error) {
       console.error(error)
      }
     },
     removeItem: (key: string) => {
      try {
       ls.remove(key)
      } catch (error) {
       console.error(error)
      }
     },
    },
   },
  ],
 },
})

You can see an example of a full implementation here here

This project is inspired by vuex-persistedstate and pinia-plugin-persist.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Changelog

Detailed changes for each release are documented in the release notes.

License

This project is under MIT license.