Giter Club home page Giter Club logo

vuex-persistedstate's Introduction

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

Installation

$ npm install vuex-persistedstate

Usage

Edit vuex-persistedstate

import createPersistedState from 'vuex-persistedstate'

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

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. (default: vuex)

  • paths <Array>: An array of any paths to partially persist the state. If no paths are given, the complete state is persisted. (default: [])

  • 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 for (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

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

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.

⚠️ 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.

License

MIT © Robin van der Vleuten

vuex-persistedstate's People

Contributors

robinvdvleuten avatar zweizeichen avatar ciceropablo avatar gurpreetatwal avatar jofftiquez avatar devoidcoding avatar jrast avatar antixrist avatar leonardpauli avatar qkdreyer avatar raphaelsaunier avatar rodneyrehm avatar wongyouth avatar atinux avatar

Stargazers

lv-kit avatar

Watchers

James Cloos avatar  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.