Git Product home page Git Product logo

vuex-persistedstate's Introduction

vuex-persistedstate

Persist and rehydrate your Vuex state between page reloads.


🚨 Not maintained anymore! As I don't use Vue in my day to day work, it becomes very hard to stay up to date with any changes with things like Vuex, Nuxt.js and other tools used by the community. That's why I decided to stop spending my spare time to this repository. Feel free to reach out if you would like to take over ownership of the package on NPM. Thank you for any contribution any of you had made to this project 🙏.


Build Status NPM version NPM downloads Prettier MIT license

PRs Welcome Code Of Conduct

Sponsored by The Webstronauts

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 { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

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

For usage with for Vuex 3 and Vue 2, please see 3.x.x branch.

Examples

Check out a basic 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)

Example with Vuex modules

New plugin instances can be created in separate files, but must be imported and added to plugins object in the main Vuex file.

/* module.js */
export const dataStore = {
  state: {
    data: []
  }
}

/* store.js */
import { dataStore } from './module'

const dataState = createPersistedState({
  paths: ['data']
})

export new Vuex.Store({
  modules: {
    dataStore
  },
  plugins: [dataState]
})

Example with Nuxt.js

It is possible to use vuex-persistedstate with Nuxt.js. It must be included as a NuxtJS plugin:

With local storage (client-side only)

// nuxt.config.js

...
/*
 * Naming your plugin 'xxx.client.js' will make it execute only on the client-side.
 * https://nuxtjs.org/guide/plugins/#name-conventional-plugin
 */
plugins: [{ src: '~/plugins/persistedState.client.js' }]
...
// ~/plugins/persistedState.client.js

import createPersistedState from 'vuex-persistedstate'

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

Using cookies (universal client + server-side)

Add cookie and js-cookie:

npm install --save cookie js-cookie or yarn add cookie js-cookie

// nuxt.config.js
...
plugins: [{ src: '~/plugins/persistedState.js'}]
...
// ~/plugins/persistedState.js

import createPersistedState from 'vuex-persistedstate';
import * as Cookies from 'js-cookie';
import cookie from 'cookie';

export default ({ store, req }) => {
    createPersistedState({
        paths: [...],
        storage: {
            getItem: (key) => {
                // See https://nuxtjs.org/guide/plugins/#using-process-flags
                if (process.server) {
                    const parsedCookies = cookie.parse(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)
        }
    })(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.

🔐Obfuscate Local Storage

If you need to use Local Storage (or you want to) but want to prevent attackers from easily inspecting the stored data, you can obfuscate it.

Important ⚠️ Obfuscating the Vuex store means to prevent attackers from easily gaining access to the data. This is not a secure way of storing sensitive data (like passwords, personal information, etc.), and always needs to be used in conjunction with some other authentication method of keeping the data (such as Firebase or your own server).

Edit vuex-persistedstate with secure-ls (obfuscated 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.

Changelog

Please see CHANGELOG for more information on what has changed recently.

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

💻 ⚠️

Quentin Dreyer

💻

Raphael Saunier

💻

Rodney Rehm

💻 ⚠️

Ryan Wang

💻 📖 ⚠️

Sébastien Chopin

📖

jeffjing

💻

macarthuror

📖

Paul Melero

📖 💻 ⚠️

Guillaume da Silva

💻

Jonathan Santerre

💻

Fábio Santos

📖

robertgr991

💻

JurijsKolesnikovs

📖

David Bond

📖

Freek van Rijt

📖

Ilyes Hermellin

💻

Peter Siska

📖

Dmitry Filippov

📖

Thomas Meitz

📖 ⚠️

Neeron Bhatta

📖

joaoaraujo-hotmart

💻

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

License

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

vuex-persistedstate's People

Contributors

adm1t avatar allcontributors[bot] avatar antixrist avatar boris-graeff avatar ciceropablo avatar davidsbond avatar dependabot-preview[bot] avatar dependabot[bot] avatar devoidcoding avatar fabiofdsantos avatar freekvr avatar gangsthub avatar gurpreetatwal avatar hughns avatar jakubkoralewski avatar jankeesvw avatar jofftiquez avatar jrast avatar juanvillegas avatar leonardpauli avatar nelsliu9121 avatar neuronbutter avatar nicolas-t avatar peschee avatar robinvdvleuten avatar santerrejo avatar wtduck avatar yachaka avatar yurakolesnikov avatar zweizeichen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vuex-persistedstate's Issues

Persisting to IndexedDB

I read in your documentation about the possibility to use another persisting location (e.g. cookies). I would like to use your library to store the Vuex values into the IndexedDB. An IndexedDB uses async methods to store the data (promises). Is it possible to use this library with those setters, without introducing a racing condition?

Otherwise, I would like to open a feature request, as it seems to be more efficient to use IndexedDB over localStorage or even cookies.

What do you think about it?

Errors when using store.replaceState() in my project

Specifically when I am attempting to reset my state object to an initial point in time:

    store.replaceState(JSON.parse(JSON.stringify(initState))) 

if vuex-persistedstate is included in my application - I get these errors thrown

vue.common.js?e881:560 [Vue warn]: Error in callback for watcher "function () { return getter(this$1.state, this$1.getters); }": 
(found in <Root>)

vue.common.js?e881:1449 TypeError: Cannot read property 'fullPath' of undefined
    at Vue$3.store.watch.sync (eval at <anonymous> (app.js:2552), <anonymous>:21:16)
    at Watcher.run (eval at <anonymous> (app.js:723), <anonymous>:2553:19)
    at Watcher.update (eval at <anonymous> (app.js:723), <anonymous>:2527:10)
    at Dep.notify (eval at <anonymous> (app.js:723), <anonymous>:638:13)
    at Object.reactiveSetter [as $$state] (eval at <anonymous> (app.js:723), <anonymous>:868:11)
    at eval (eval at <anonymous> (app.js:761), <anonymous>:375:30)
    at Store._withCommit (eval at <anonymous> (app.js:761), <anonymous>:409:3)
    at Store.replaceState (eval at <anonymous> (app.js:761), <anonymous>:374:8)
    at eval (eval at <anonymous> (app.js:1468), <anonymous>:48:57)
    at wrappedMutationHandler (eval at <anonymous> (app.js:761), <anonymous>:598:5)
handleError @ vue.common.js?e881:1449
run @ vue.common.js?e881:2555
update @ vue.common.js?e881:2527
notify @ vue.common.js?e881:638
reactiveSetter @ vue.common.js?e881:868
(anonymous) @ vuex.esm.js?edaa:370
_withCommit @ vuex.esm.js?edaa:404
replaceState @ vuex.esm.js?edaa:369
(anonymous) @ mutations.js?90ae:50
wrappedMutationHandler @ vuex.esm.js?edaa:593
commitIterator @ vuex.esm.js?edaa:317
(anonymous) @ vuex.esm.js?edaa:316
_withCommit @ vuex.esm.js?edaa:404
commit @ vuex.esm.js?edaa:315
boundCommit @ vuex.esm.js?edaa:271
getStarted @ Home.vue?d594:46
boundFn @ vue.common.js?e881:126
invoker @ vue.common.js?e881:1660

Encryption

Do you think of encrypting datas saved in localstorage or set with a cookie ?

vuex-persistedstate with Nuxtjs

Is it possible to use vuex-persistedstate with nuxtjs? (with server side rendering on)

My current store looks like this:

import { Store } from 'vuex';

import createPersistedState from 'vuex-persistedstate';
import * as Cookie from 'js-cookie';

const store = () => new Store({
    state: {
        counter: 0
    },

    getters: {
        counter(state) {
            return state.counter;
        }
    },

    mutations: {
        increment(state) {
            state.counter++;
        }
    },

    plugins: [
        createPersistedState({
            storage: {
                paths: ['counter'],
                getItem: (key) => Cookie.getJSON(key),
                setItem: (key, value) => Cookie.set(key, value, { expires: 3, secure: true }),
                removeItem: (key) => Cookie.remove(key)
            }
        })
    ]
});


export default store;

I am not getting any errors but the store doesn't persist. Am I doing anything wrong or is this feature not possible with nuxt ssr right now?

I've seen #44 and I followed the instructions by @robinvdvleuten. That doesn't work so that's why I made this issue.

Small error in the 'Customize Storage' sample snippet?

Hi,

First of all, great plugin over here, I could solve my data persistence problem.

While using your plugin along with js-cookie, my app could not keep the state when refreshing the page and then I noticed that the getItem function in the provided example was using the function Cookies.getJSON(key) to retrieve the parsed data. So I changed it to retrieve the unparsed data (Cookies.get(key)) and worked beautifully.

Perhaps a little error in there or I failed to understand your plugin. Anyway, thanks again for your plugin!

vuex state 'tokens' not saved to cookie in debug mode

vuex state 'tokens' not saved to cookie in debug mode,the code as following,Are there any wrong?

Reference sample code:
https://github.com/robinvdvleuten/vue-auth0-vuex/blob/master/template/src/store/index.js#L14

import Vue from 'vue'
import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'
import createPersistedState from 'vuex-persistedstate' //vuex持久化localstorage插件
import * as Cookies from 'js-cookie';
import * as state from './state'
import * as mutations from './mutations'
import * as actions from './actions'
import * as getters from './getters'
import menu from './modules/menu'
import login from './modules/login'

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  modules: {
    menu,
    login
  },
  strict: debug,
  plugins: debug ? [createLogger(), createPersistedState({
      paths: ['login.tokens'],
      getState: (key) => Cookies.getJSON(key),
      setState: (key, state) => Cookies.set(key, state, {expires: 300000000, secure: true})
    })] : [createPersistedState()]
})

Nested keys?

Hey, not sure if this just my lack of knowledge about localStorage, but everything seems to be stored with a nested key at the moment, resulting in data structures like this when inspecting localStorage:

settings: {
    settings: {
        foo: "bar"
    }
}

Is this expected, or have I done something weird with the config? Note that when retrieving using the data in my application it behaves as expected, i.e. using a getter for settings gives me:

settings: {
    foo: "bar"
}

reducer removes object from state entirely NOT just persisted-state NOT SOLVED

const persistedStateOptions = {
  reducer: function (state, paths) {
   // No need to use let as the reducer itself can be immutable which do not mean that the properties are not mutable (https://ponyfoo.com/articles/var-let-const)
    let reducer = Object.assign({}, state)
    // state which you don't want to persist.
    delete reducer.module.objectname

    return reducer
  }
}
const options = {
...
  plugins: [createPersistedState(persistedStateOptions)]
}
export default new Vuex.Store(options)

Then when I view the state via the Vue Chrome plugin, the objectname no longer appears in the state.
If I comment out the delete line above, the object appears.
I tried both let reducer and const reducer just in case that made a difference.

The problem is that the object above exceeds the quota for the internal storage. I need to remove that object from being persisted BUT keep it in the Vuex state.

The following code complains of an undefined property error
const cognitoUser = cloneDeep(state.cognitoUser);
Help!!

Deleting items from persisted array

I'm having an issue forcing deleted array items persist. It seems the new array is just merged to the old array rather than replacing it in the mutation function. Is there a specific way you need to delete items from the array? I'm able to change values and make those persist fine.

Thanks!

How does this work?

Sorry, this is a stupid question... but how does this work?

I have:

import user from './modules/user';
Vue.use(Vuex);

export const store = new Vuex.Store({
  modules: {
    user,
    plugins: [ createPersistedState({
      paths: [ 'user' ]
    })]
  }
});

and in user module I have this:

const state = {
  currentUser: null,
  userAds: null
};

So I was kinda expecting that whatever code updates that currentUser, this plugin would automatically push it to localStorage. What steps am I missing (as what I'm doing clearly isn't working). Is there anything else, anywhere else I need to add/configure?

Thank you!

Issue after register module

So i mage a plugin for vue and am working on a demo project. So i wanted to add your localstorrage and it works awesome.

My plugin: https://github.com/disjfa/vue-route-timeline / https://disjfa.github.io/vue-route-timeline/
My template: https://github.com/disjfa/kazoo / https://disjfa.github.io/kazoo

The store gets persisted like it would, but my store module in my plugin is not updated with the store. I think it is because your store items gets set before the store.registerModule(moduleName, timelineStore); in my plugin gets called. So the state of my plugin gets reset.

You can check it out by clicking in my app and on the homepage the list grows. But on f5 it's cleaned again. It does gets stored in the localstorage by the way.

If i can help or know where to look i can help.

Couple of questions

Hey,

Thank you for this package, I'm looking forward to digging in.

First question, Is it possible to use this without storing them under one global key? And have them under separate keys?

The reason for this is that I have an existing application where users have info stored in a few different localStorage keys.

Or would you suggest migrating this information into a single key?

Secondly, is there a way that when a user first loads my app - the data that's already in localStorage is then sync with my store? Can this be done using getState?

I hope you can help.

Thanks

unhandled json parsing exceptions

Noticed that json parsing exception are not handled. if the value is not proper json will end up in:
Uncaught SyntaxError: Unexpected token in JSON

I guess it might be handled later on, but does break the example

return value && value !== 'undefined' ? JSON.parse(value) : undefined;

Caching Authorization Token for future re-use

Hello,

I am trying to figure out https://jsfiddle.net/robinvdvleuten/wmf8zvf8/ .
Is there a logic hidden somewhere that takes the localStorage if available ?
I am using the plugin to store a JWT (Authorization token) and as I am explicitly doing:

const state = JSON.parse(localStorage.getItem('persistedState'));
const config = {
  headers: {
    Authorization: `Bearer ${state.tokens.token.accessToken}`,
  },
};

I get errors when localStorage is empty.
Naturally I could add a condition to check for that but from your example it seems that's already part of the plugin.

How to invalidate the stored state?

Hey, I would be really happy if there way an easy way to decide whether or not to actually restore the state, based on some condition.

My use case is (roughly) that I have the app running at /app, and it may or may not receive some GET parameters when it loads. If a GET parameter is equal to X, but the stored state was made with the get parameter Y, those states shouldn't override.

The only solution I can think of is to make the store key dynamic, by using the GET parameter as part of the name (eg. key = "myApp"+idFromGet), but I don't know how much of a hack that would be.

Or perhaps using js-cookie and using a dynamic key there?

Any input is much appreciated, thanks.

Using default state (first load)

How do I define an initial state object assuming the user is visiting for the first time? My mutations will fail (I assume) if I attempt to modify keys on the object that do not already exist.

My current setup for example:

export const state = {
    settings: {},
    missions: [],
    preference: {},
    stats: {
        summary: {},
        terrains: [],
        attendance: [],
    }
}

export const mutations = {

    setSettings(state, settings) {
        state.settings = settings
    },

    setMissionList(state, missions) {
        state.missions = missions
    },

    setStatsTerrains(state, terrains) {
        state.stats.terrains = terrains
    },

    setStatsAttendance(state, attendance) {
        state.stats.attendance = attendance
    },

    setPreferenceLanguage(state, locale) {
        state.preference.locale = locale
    },
}
import { state, mutations } from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
    state,
    mutations,
    //plugins: [createPersistedState()]
})

subscribe vs watch

Hello,
I just wondering why you are using subscribe+filter instead of watch+{ deep: true } ?

Vue.js SSR: ReferenceError: window is not defined

I am trying to implement firebase authentication on a vue.js, vuex project.
I think this module will help to persiste store data both in server and client sides.
But i got this error : ReferenceError: window is not defined

 DONE  Compiled successfully in 17433ms                                                                                     11:38:23 AM

webpack built 885a204769e45af74490 in 17433ms
error during render : /
ReferenceError: window is not defined
    at createPersistedState (/home/badis/Desktop/vue-hackernews-2.0/node_modules/vuex-persistedstate/dist/vuex-persistedstate.js:54:66)
    at createStore (src/store/index.js:30:14)
    at createApp (src/app.js:21:16)
    at module.exports.__webpack_exports__.default (src/entry-server.js:13:35)
    at module.exports.__webpack_exports__.default (src/entry-server.js:11:9)
    at /home/badis/Desktop/vue-hackernews-2.0/node_modules/vue-server-renderer/build.js:7854:15
    at /home/badis/Desktop/vue-hackernews-2.0/node_modules/vue-server-renderer/build.js:7816:14
    at Object.renderToString (/home/badis/Desktop/vue-hackernews-2.0/node_modules/vue-server-renderer/build.js:7984:9)
    at render (/home/badis/Desktop/vue-hackernews-2.0/server.js:100:12)
    at readyPromise.then (/home/badis/Desktop/vue-hackernews-2.0/server.js:112:27)

How ssr apps handle : localstorage, cookies, sessions ... etc. that are only available on browser ?
Does my approache make sense ?

Just curiosity

When the plugin is using the localStorage and a refresh happends internally it is just commiting a mutation to kept in sync with the store and if I declare a mutation that mutate the state this is pick up by the plugin, if so what is the best way of doing it? I am making my own for more specific needs and I will appreciate your tips and answer.

Are you changing the state directly from within the plugin?

By the way awesome plugin...

does not load saved state in nuxt

I try to use it in nuxt:

store/index:

let plugins = []
if(process.browser) {
    plugins = plugins.concat(createPersistedState())
}
export { plugins }

The state is persisted in localstorage but not loaded when I reload the page

Cant Use Cookie For Vuex Module Namespace

I tried the Default Declation of createPersistedState() , localstorage works fine...
But I Need to Use Cookies , But I Cant See The Cookie can someone help me with this

import { Store } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
/* Add Below All Your Modules */
import auth from './modules/auth'
import permission from './modules/permission'

export default new Store({
    modules: {
        auth,
        permission
        // add modules here
    },
    plugins: [createPersistedState({
        key: App.site.trademark,
        // Declare All The State We Want to Persist
        paths: ['auth.isLoggedIn'],
        storage: {
            getItem: key => Cookies.get(key),
            setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }),
            removeItem: key => Cookies.remove(key)
        }
    })]
})

Local Storage is not initalizing

Hi Robin,
Here is the issue Im having.
I installed the package from npm
I setup my store.ts (yeah Im one of those TypeScript kids)

import * as Vue from 'vue';
import * as Vuex from 'vuex';
import * as createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex);

export const store  = new Vuex.Store({
    state: {
        AppName : "BillAndTedsExcellentApp",
        UserID: 0,
        Crumb: '',
        GPSInsightToken:'',
        HeaderNavItems : [],
        PageOptions : [] 
    },
    plugins: [createPersistedState()]
});

Then when the app recompiles, when I look in the inspector there is nothing for my app listed under LocalStorage.

I tried specifying a key to use my app name instead of your default.

So, it may just be my lack of understanding here, but does it not automatically serialize the items I have listed in my State?

Thanks,
John (YukidamaGame)

can set expire time and specify state

Do you plan to support the following functions:
1.Specify state value to persiste and set expire time,ex:
const state = {
tokens: ''
}

==>
createPersistedState([{tokens:3600}]) //only Persist state ‘tokens’(Other states are not persistent
) and setting expire time =3600ms

Duration of localstorage

Hello,
Thanks for your awesome module
How to set a duration for localstorage like 5 mins ?

Thanks

if the actions type are promise?

After I add the plugin are wrong:
Uncaught (in promise) TypeError: Converting circular structure to JSON at JSON.stringify (<anonymous>) at setState (eval at <anonymous>
on the line : vuex-persistedstate.js?2e1f:80

The following is my actions:
myactions

Problem loading state with localForage

I configured vuex-persistedstate two different ways:

  1. The default way with localStorage. Everything works great.
  2. Using localForage. The data is correctly saved in the local IndexedDB, but it is not loaded on page reload. Am i missing something?
  import Vue from 'vue'                                                                                                                                                                                  
  import Vuex from 'vuex'                                                                                                                                                                                
  import createPersistedState from 'vuex-persistedstate'                                                                                                                                                 
  import * as localforage from 'localforage'                                                                                                                                                             
  import settings from './modules/settings'                                                                                                                                                              
                                                                                                                                                                                                         
  Vue.use(Vuex)                                                                                                                                                                                          
                                                                                                                                                                                                         
  const debug = process.env.NODE_ENV !== 'production'                                                                                                                                                    
                                                                                                                                                                                                         
  export default new Vuex.Store({                                                                                                                                                                        
    plugins: [createPersistedState({storage: localforage.createInstance({name: 'bayonet'})})],                                                                                                           
    modules: {                                                                                                                                                                                           
      settings                                                                                                                                                                                           
    },                                                                                                                                                                                                   
    strict: debug                                                                                                                                                                                        
  })                                                                                                                                                                                                     

Thank you

Make compatible with SSR

Would be nice if vuex-persistedstate is compatible with server side rendering.

Could be done to store the state in cookies for server side. Tried out a little example:

import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

export const plugins = [ createPersistedState({
  getState: (key) => Cookies.getJSON(key),
  setState: (key, state) => Cookies.set(key, state, { expires: 1, secure: false })
}) ]

But it's failing because the defaults are referencing localStorage and window object.

line 57: var storage = ref.storage; if ( storage === void 0 ) storage = window && window.localStorage;

Resulting in the following error:

ReferenceError: window is not defined

How can I retrieve data from localStorage?

From what I'm understanding from the documentation and my trials, this plugin reads from the states and sets objects converted into JSON in the localStorage.

Now, if I need to create some logic based on data in the storage, where and how should I do that?
I need to check if the user is authenticated (I'm setting is token id manually outside of the plugin)

localStorage.setItem('id_token', token)

if he is and he had previously added some items to the cart (which get saved normally by the plugin)

{ key: 'cart', storage: localStorage, paths: [ 'cartModule.cart' ], }

I need to grab those items and make post request with axios.
Logging the cart "localStorage.getItem('cart')" from my action results in a JSON formatted object, which I could convert but I'm not sure if this is how this plugin is meant to be used.

{"cartModule":{"cart":[{"id":66,"beat":{"id":3,"name":"Issues","producer":{"display_name":"Test Producer","paypal_em.........

How should I dynamically set and get the data using the plug in and communicating with my store?
I think it would be nice to have a more descriptive documentation, i find it hard to follow as a newbie.

Thank you!

Example needed

I am trying to implement vuex-persistedstate but I don't understand how to update the state in the local storage.

import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

const store = new Vuex.Store({
  plugins: [
    createPersistedState({
      getState: (key) => Cookies.getJSON(key),
      setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true })
    })
  ],
  state: {
    counter: 0,
    showLogin: false,
    loggedIn: false,
    showIntro: true
  },
  mutations: {
    toggleLogin (state) {
      state.showLogin = !state.showLogin
    },
    toggleIntro (state) {
      state.showIntro = !state.showIntro
    }
  }
})
export default store

This is the code I have at this moment. I do see that a local storage is added in my web inspector but unfortunately it's not updated when I trigger a state mutation. How should I trigger the mutation to also update the local storage?

Persist only part of path (but keep all of it in memory)

Is there any way to partially persist a path in the vuex state in localStorage and still keep the rest in the vuex state but only memory?

So I expected to be able to tackle this problem with a reducer function to only persist what I wanted.

In the code below the reducer function aims to persist any texts written by the currently logged in user (state.User.user.id) so they can be accessible even if the client is offline. However, this effectively filtered any texts NOT written by the current user out of vuex altogether.

Is there any way for localStorage to coexist with the in-memory store that vuex uses out of the box?

import _ from 'lodash'

const reducer = (state, paths) => (
  paths.length === 0 ? state : paths.reduce((substate, path) => {
    const value = _.get(state, path)

    switch (path) {
      case 'texts':
        // Only persist texts which are submitted by the current user
        value.items = value.items.filter(item =>
          (item.user && item.user.id === state.User.user.id))
        break
    }

    _.set(substate, path, value)

    return substate
  }, {})
)

export default reducer

How could i retrieve the data from sessionStorage. the data isn't exist when the page loaded

I have tow Browser taps, tap one i had login my account and put the data to sessionStorage( tap one ), when i swith to tap two, i enter the url ( the url of tap one ) and get the data of sessionStorge from tap one, and then i put it to sessionStorage( tap two ), so i need to retieve data from sessionStorage for state. ( fresh the page could to do that, but it's not friendly from the user ), could you help me that, thank you very much.

Restoring state for dynamically registered modules

I noticed that when the modules are registered dynamically it doesn't restore the state persisted in localstorage. I have an empty store which initialized with this plugin and modules are registered dynamically after that.

Is there any way to overcome this limitation?

[question] reset state

How do I reset state to how it's defined in my store?
During development, I sometimes change the state object by removing properties.
However, after clearing localStorage/reloading, the removed props + data come up again.
Where does the plugin persist the state? Can I clear it programmatically?

const state     = {
  list: [],
// testField comes up again in localStorage, although removed in vuex state
 //testField: '', 
}

Error Uncaught TypeError: Converting circular structure to JSON

Using the basic example I am getting a circular structure error
I suspect the actual issue is elsewhere but I don't know where to look.


import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate'

// Added Modules
import auth from './modules/auth'; 
import site from './modules/site'; 

const store = new Vuex.Store({
  modules: {
    auth,
    site
  },
  state: {},
  plugins: [createPersistedState()]  
});

export default store;

Storage bug after reload

I don't know if this is the browser, workspace or problem of your plugin and I am going crazy.
After page refresh ... mostly I am not able to change some values by calling mutation, but some of them works fine.

If you have time otherwise delete this, thank you =)

store.subscribe not being triggered

Hi,

I'm using vuex-persistedstate and I need to subscribe to the "value resetting event".

I added store.subscribe to my store but it is not being triggered when the values are put back after refresh.

Amu I missing something?

Thanks

Will it sync store between tabs?

Hi. Will this plugin sync store between tabs? I mean, if an app is opened in two tabs, I commit something to vuex, it is pushed to localstore, will the vuex in second tab catch it up?

Promise Support

Hi, say I use localForage or PouchDB, currently it's not working with the lib

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.