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

@pinian/persistent-state

v1.1.0

Published

This plugin provides effortless state persistence for Pinia stores with a flexible, easy-to-use API. From simple defaults to advanced customizations like multi-storage and serializers, it streamlines state management, making it a perfect fit for any proje

Downloads

130

Readme

@pinian/persistent-state

This plugin offers effortless state persistence for Pinia stores with a flexible, easy-to-use API. From simple defaults to advanced customizations like multi-storage and serializers, it streamlines state management through a single persistentState option, making it a perfect fit for any project.

Features

  • Effortless State Persistence: Automatically saves and loads your store's state, ensuring a seamless experience across sessions and page reloads.
  • Flexible Storage Options: Choose between localStorage, sessionStorage, or even define your own custom storage solution to fit your needs.
  • Granular Control: Configure persistence for the entire store or fine-tune it to save specific parts of your state with ease.
  • XSS Protection: Protect your state from XSS by sanitizing data during both save and load, ensuring only clean information is used.
  • Zero Dependencies: This plugin is built with zero external dependencies, ensuring minimal overhead and maximum compatibility with any project setup.

Quick Start

  1. Install the plugin:
npm install @pinian/persistent-state
  1. Register the plugin with Pinia:
import { createPinia } from 'pinia';
import { createPersistentState } from '@pinian/persistent-state';

const pinia = createPinia();
pinia.use(createPersistentState());
  1. Add the persistentState option to the store you want to be persisted:
import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
    },
  }),
  persistentState: true,
});

Your store will be saved using the default configuration.

Configuration

The plugin provides flexible configuration options that can be applied in two main ways:

  1. Globally: Set configuration options that apply to all stores during plugin initialization. This is useful when you want consistent behavior across all your stores without repeating configuration.
  2. Locally (Per Store): Override global settings or specify custom settings for individual stores by using the persistentState option within the store definition.

Global Configuration

To apply configurations globally, pass them when registering the plugin with Pinia:

import { createPinia } from 'pinia';
import { createPersistentStatePlugin } from '@pinian/persistent-state';

const pinia = createPinia();
pinia.use(createPersistentStatePlugin({
  auto: true,
  key: (id) => `v1.0.0-${id}`,
  storage: localStorage,
  serialize: (state) => btoa(JSON.stringify(state)),
  deserialize: (state) => JSON.parse(atob(state)),
}));

Local Configuration

For specific stores, you can use the persistentState option to override the global settings or define custom behavior. There are three ways to configure persistentState for a store:

  1. Boolean (true): Use global defaults to persist the entire store state.
import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
    },
  }),
  persistentState: true,
});
  1. Object: Define custom settings for the store, such as custom keys, specific storage, or choosing paths to persist.
import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
      password: 'secret',
    },
    settings: {
      theme: 'dark',
    },
  }),
  persistentState: {
    key: (id) => `v1.0.0-${id}`,
    storage: localStorage,
    serialize: (state) => btoa(JSON.stringify(state)),
    deserialize: (state) => JSON.parse(atob(state)),
    pickPaths: [
      'user',
      'settings',
    ],
    omitPaths: [
      'user.password',
    ],
  },
});
  1. Array of Objects: If you need to apply more complex persistence logic, such as storing different parts of the state in different storages, you can use an array of configuration objects.
import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
      password: 'secret',
    },
    settings: {
      theme: 'dark',
    },
  }),
  persistentState: [
    {
      key: (id) => `v1.0.0-${id}`,
      storage: localStorage,
      serialize: (state) => btoa(JSON.stringify(state)),
      deserialize: (state) => JSON.parse(atob(state)),
      pickPaths: [
        'user',
      ],
      omitPaths: [
        'user.password',
      ],
    },
    {
      storage: sessionStorage,
      serialize: (state) => JSON.stringify(state),
      deserialize: (state) => JSON.parse(state),
      pickPaths: [
        'settings.theme',
      ]
    },
  ],
});

Options

auto

  • type: boolean
  • default: false
  • scope: Global

Defines whether state persistence should be enabled by default for all stores. This can be useful when you want to save the entire application state to browser storage without explicitly configuring each store.

import { createPinia } from 'pinia';
import { createPersistentStatePlugin } from '@pinian/persistent-state';

const pinia = createPinia();
pinia.use(createPersistentStatePlugin({
  auto: true,
}));

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
    },
  }),
});

This configuration will automatically enable state persistence for all stores with the specified default settings. This ensures state preservation between page reloads without manual configuration for each store.

key

  • type: (id: string) => string
  • default: (id) => id
  • scope: Global and Local

Defines a custom key to identify the store's state in the selected storage.

import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
    },
  }),
  persistentState: {
    key: (id) => `prefix-${id}`,
  },
});

This store will be saved under the prefix-profile key in localStorage.

storage

  • type: KeyValueStorage
  • default: localStorage
  • scope: Global and Local

Defines which storage mechanism to use. It can be localStorage, sessionStorage, or a custom implementation of the KeyValueStorage interface.

import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
    },
  }),
  persistentState: {
    storage: sessionStorage,
  },
});

This store will be saved using sessionStorage instead of localStorage.

serialize

  • type: (state: T) => string
  • default: JSON.stringify
  • scope: Global and Local

Defines how to serialize the state into a string before saving it. You can also provide a custom serialization method if needed.

import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
    },
  }),
  persistentState: {
    serialize: (state) => btoa(JSON.stringify(state)),
  },
});

This store will save the state using Base64 encoding.

deserialize

  • type: (state: string) => T
  • default: JSON.parse
  • scope: Global and Local

Defines how to deserialize the string from storage back into the state object. You can also provide a custom deserialization method if needed.

import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
    },
  }),
  persistentState: {
    deserialize: (state) => JSON.parse(atob(state)),
  },
});

This store will load the state from Base64 encoding.

pickPaths

  • type: string[]
  • default: []
  • scope: Local

Defines which paths of the state should be saved. You can specify only the paths you want to store.

import { defineStore } from 'pinia';

export const useStore = defineStore('profile', {
  state: () => ({
    user: {
      name: 'John Doe',
      password: 'secret',
    },
    settings: {
      theme: 'dark',
    },
  }),
  persist: {
    pickPaths: [
      'user.name',
      'settings.theme',
    ],
  },
});

This store will only save user.name and settings.theme, ignoring other state fields.

omitPaths

  • type: string[]
  • default: []
  • scope: Local

Defines which paths of the state should not be saved. All other paths will be stored.

import { defineStore } from 'pinia';

export const useStore = defineStore('main', {
  state: () => ({
    user: {
      name: 'John Doe',
      password: 'secret',
    },
    settings: {
      theme: 'dark',
    },
  }),
  persist: {
    omitPaths: [
      'user.password',
    ],
  },
});

This store will save everything except user.password.

License

@pinian/persistent-state is released under the MIT License.