soc221b / pinia-plugin-persistedstate-2

Persist and rehydrate your Pinia state between page reloads.
https://www.npmjs.com/package/pinia-plugin-persistedstate-2
MIT License
89 stars 8 forks source link
async localforage localstorage pinia plugin storage vue

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

🚀 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

IStorage

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
    },
  },
)

Store Properties

🤝 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