Skip to content

๐Ÿ’พ Persist and rehydrate your Vuex state between page reloads.

License

Notifications You must be signed in to change notification settings

sfyr111/vuex-persistedstate

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

vuex-persistedstate

Persist and rehydrate your Vuex state between page reloads.


Build Status NPM version NPM downloads Prettier MIT license

PRs Welcome Code Of Conduct

Requirements

Install

npm install --save vuex-persistedstate

The UMD build is also available on unpkg:

<script src="https://unpkg.com/vuex-persistedstate/dist/vuex-persistedstate.umd.js"></script>

You can find the library on window.createPersistedState.

Usage

import createPersistedState from "vuex-persistedstate";

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()],
});

Check out the example on CodeSandbox.

Edit vuex-persistedstate

Or configured to use with js-cookie.

Edit vuex-persistedstate with js-cookie

Or configured to use with secure-ls

Edit vuex-persistedstate with secure-ls (encrypted data)

Nuxt.js

It is possible to use vuex-persistedstate with Nuxt.js. Due to the order code is loaded in, vuex-persistedstate must be included as a NuxtJS plugin:

// nuxt.config.js

...
plugins: [{ src: '~/plugins/localStorage.js', ssr: false }]
...
// ~/plugins/localStorage.js

import createPersistedState from 'vuex-persistedstate'

export default ({store}) => {
  window.onNuxtReady(() => {
    createPersistedState({
        key: 'yourkey',
        paths: [...]
        ...
    })(store)
  })
}

API

createPersistedState([options])

Creates a new instance of the plugin with the given options. The following options can be provided to configure the plugin for your specific needs:

  • key <String>: The key to store the persisted state under. Defaults to vuex.

  • paths <Array>: An array of any paths to partially persist the state. If no paths are given, the complete state is persisted. If an empty array is given, no state is persisted. Paths must be specified using dot notation. If using modules, include the module name. eg: "auth.user" Defaults to undefined.

  • reducer <Function>: A function that will be called to reduce the state to persist based on the given paths. Defaults to include the values.

  • subscriber <Function>: A function called to setup mutation subscription. Defaults to store => handler => store.subscribe(handler).

  • storage <Object>: Instead of (or in combination with) getState and setState. Defaults to localStorage.

  • getState <Function>: A function that will be called to rehydrate a previously persisted state. Defaults to using storage.

  • setState <Function>: A function that will be called to persist the given state. Defaults to using storage.

  • filter <Function>: A function that will be called to filter any mutations which will trigger setState on storage eventually. Defaults to () => true.

  • overwrite <Boolean>: When rehydrating, whether to overwrite the existing state with the output from getState directly, instead of merging the two objects with deepmerge. Defaults to false.

  • arrayMerger <Function>: A function for merging arrays when rehydrating state. Defaults to function (store, saved) { return saved } (saved state replaces supplied state).

  • rehydrated <Function>: A function that will be called when the rehydration is finished. Useful when you are using Nuxt.js, which the rehydration of the persisted state happens asynchronously. Defaults to store => {}

  • fetchBeforeUse <Boolean>: A boolean indicating if the state should be fetched from storage before the plugin is used. Defaults to false.

  • assertStorage <Function>: An overridable function to ensure storage is available, fired on plugins's initialization. Default one is performing a Write-Delete operation on the given Storage instance. Note, default behaviour could throw an error (like DOMException: QuotaExceededError).

Customize Storage

If it's not ideal to have the state of the Vuex store inside localstorage. One can easily implement the functionality to use cookies for that (or any other you can think of);

Edit vuex-persistedstate with js-cookie

import { Store } from "vuex";
import createPersistedState from "vuex-persistedstate";
import * as Cookies from "js-cookie";

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => 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: 3, secure: true }),
        removeItem: (key) => Cookies.remove(key),
      },
    }),
  ],
});

In fact, any object following the Storage protocol (getItem, setItem, removeItem, etc) could be passed:

createPersistedState({ storage: window.sessionStorage });

This is especially useful when you are using this plugin in combination with server-side rendering, where one could pass an instance of dom-storage.

๐Ÿ”Encrypted Local Storage

If you need to use Local Storage (or you want to) but needs to protect the content of the data, you can encrypt it.

Edit vuex-persistedstate with secure-ls (encrypted data)

import { Store } from "vuex";
import createPersistedState from "vuex-persistedstate";
import SecureLS from "secure-ls";
var ls = new SecureLS({ isCompression: false });

// https://github.com/softvar/secure-ls

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => ls.get(key),
        setItem: (key, value) => ls.set(key, value),
        removeItem: (key) => ls.remove(key),
      },
    }),
  ],
});

โš ๏ธ LocalForage โš ๏ธ

As it maybe seems at first sight, it's not possible to pass a LocalForage instance as storage property. This is due the fact that all getters and setters must be synchronous and LocalForage's methods are asynchronous.

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Robin van der Vleuten

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ

Sebastian

๐Ÿ’ป ๐Ÿ“–

Boris Graeff

๐Ÿ’ป

Cรญcero Pablo

๐Ÿ“–

Gurpreet Atwal

โš ๏ธ

Jakub Koralewski

๐Ÿ’ป

Jankees van Woezik

๐Ÿ“–

Jofferson Ramirez Tiquez

๐Ÿ“–

Jordan Deprez

๐Ÿ“–

Juan Villegas

๐Ÿ“–

Jรผrg Rast

๐Ÿ’ป

Kartashov Alexey

๐Ÿ’ป

Leonard Pauli

๐Ÿ’ป ๐Ÿ“–

Nelson Liu

๐Ÿ’ป ๐Ÿ“– โš ๏ธ

Nico

๐Ÿ’ป โš ๏ธ

Paul Melero

๐Ÿ“–

Quentin Dreyer

๐Ÿ’ป

Raphael Saunier

๐Ÿ’ป

Rodney Rehm

๐Ÿ’ป โš ๏ธ

Ryan Wang

๐Ÿ’ป ๐Ÿ“– โš ๏ธ

Sรฉbastien Chopin

๐Ÿ“–

jeffjing

๐Ÿ’ป

macarthuror

๐Ÿ“–

Paul Melero

๐Ÿ“– ๐Ÿ’ป โš ๏ธ

Guillaume da Silva

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

License

The MIT License (MIT). Please see License File for more information.

About

๐Ÿ’พ Persist and rehydrate your Vuex state between page reloads.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 78.1%
  • TypeScript 21.9%