Coder Social home page Coder Social logo

tanimodori / pinia-plugin-persistedstate-2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from soc221b/pinia-plugin-persistedstate-2

0.0 0.0 0.0 5.13 MB

Persist and rehydrate your Pinia state between page reloads

License: MIT License

Shell 0.28% JavaScript 8.40% TypeScript 91.32%

pinia-plugin-persistedstate-2's Introduction

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 Bundle size

Conventional Commits Prettier

PRs Welcome

donate donate

โœจ Features

  • ๐ŸŽจ Configurable globally and in every store.
  • ๐Ÿ’ช Type Safe
  • ๐Ÿ“ฆ Extremely small

๐Ÿš€ Getting Started

Installation

Package Manager

# npm
npm i pinia-plugin-persistedstate-2

# yarn
yarn add pinia-plugin-persistedstate-2

# pnpm
pnpm add 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

pinia-plugin-persistedstate-2's People

Contributors

a-mazalov avatar github-actions[bot] avatar renovate[bot] avatar reslear avatar seanohue avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.