Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/robinvdvleuten/vuex-persistedstate
πΎ Persist and rehydrate your Vuex state between page reloads.
https://github.com/robinvdvleuten/vuex-persistedstate
hacktoberfest localstorage plugin storage vue vuex
Last synced: 2 months ago
JSON representation
πΎ Persist and rehydrate your Vuex state between page reloads.
- Host: GitHub
- URL: https://github.com/robinvdvleuten/vuex-persistedstate
- Owner: robinvdvleuten
- License: mit
- Archived: true
- Created: 2016-09-25T14:11:33.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2022-02-04T09:16:15.000Z (almost 3 years ago)
- Last Synced: 2024-09-25T19:45:25.011Z (3 months ago)
- Topics: hacktoberfest, localstorage, plugin, storage, vue, vuex
- Language: JavaScript
- Homepage: https://npm.im/vuex-persistedstate
- Size: 1.04 MB
- Stars: 5,761
- Watchers: 51
- Forks: 379
- Open Issues: 27
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: .github/CODE_OF_CONDUCT.md
Awesome Lists containing this project
- stars - robinvdvleuten/vuex-persistedstate
- xhlf-awesome - vuex-persistedstate
README
# vuex-persistedstate
Persist and rehydrate your [Vuex](http://vuex.vuejs.org/) 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](https://img.shields.io/github/workflow/status/robinvdvleuten/vuex-persistedstate/test.svg)](https://github.com/robinvdvleuten/vuex-persistedstate/actions?query=workflow%3Atest)
[![NPM version](https://img.shields.io/npm/v/vuex-persistedstate.svg)](https://www.npmjs.com/package/vuex-persistedstate)
[![NPM downloads](https://img.shields.io/npm/dm/vuex-persistedstate.svg)](https://www.npmjs.com/package/vuex-persistedstate)
[![Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
[![MIT license](https://img.shields.io/github/license/robinvdvleuten/vuex-persistedstate.svg)](https://github.com/robinvdvleuten/vuex-persistedstate/blob/master/LICENSE)[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com)
[![Code Of Conduct](https://img.shields.io/badge/code%20of-conduct-ff69b4.svg)](https://github.com/robinvdvleuten/vuex-persistedstate/blob/master/.github/CODE_OF_CONDUCT.md)## Install
```bash
npm install --save vuex-persistedstate
```The [UMD](https://github.com/umdjs/umd) build is also available on [unpkg](https://unpkg.com):
```html
```
You can find the library on `window.createPersistedState`.
## Usage
```js
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](https://github.com/robinvdvleuten/vuex-persistedstate/tree/3.x.x).
## Examples
Check out a basic example on [CodeSandbox](https://codesandbox.io).
[![Edit vuex-persistedstate](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/80k4m2598)
Or configured to use with [js-cookie](https://github.com/js-cookie/js-cookie).
[![Edit vuex-persistedstate with js-cookie](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/xl356qvvkz)
Or configured to use with [secure-ls](https://github.com/softvar/secure-ls)
[![Edit vuex-persistedstate with secure-ls (encrypted data)](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/vuex-persistedstate-with-secure-ls-encrypted-data-7l9wb?fontsize=14)
### 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.
```js
/* 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)
```javascript
// 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' }]
...
``````javascript
// ~/plugins/persistedState.client.jsimport 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````javascript
// nuxt.config.js
...
plugins: [{ src: '~/plugins/persistedState.js'}]
...
``````javascript
// ~/plugins/persistedState.jsimport 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 `: The key to store the persisted state under. Defaults to `vuex`.
- `paths `: 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 `: A function that will be called to reduce the state to persist based on the given paths. Defaults to include the values.
- `subscriber `: A function called to setup mutation subscription. Defaults to `store => handler => store.subscribe(handler)`.- `storage `: Instead of (or in combination with) `getState` and `setState`. Defaults to localStorage.
- `getState `: A function that will be called to rehydrate a previously persisted state. Defaults to using `storage`.
- `setState `: A function that will be called to persist the given state. Defaults to using `storage`.
- `filter `: A function that will be called to filter any mutations which will trigger `setState` on storage eventually. Defaults to `() => true`.
- `overwrite `: 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 `: A function for merging arrays when rehydrating state. Defaults to `function (store, saved) { return saved }` (saved state replaces supplied state).
- `rehydrated `: 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 `: A boolean indicating if the state should be fetched from storage before the plugin is used. Defaults to `false`.
- `assertStorage `: 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](https://github.com/js-cookie/js-cookie) for that (or any other you can think of);
[![Edit vuex-persistedstate with js-cookie](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/xl356qvvkz?autoresize=1)
```js
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:
```js
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](https://www.npmjs.com/package/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]('https://github.com/softvar/secure-ls').
**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)](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/vuex-persistedstate-with-secure-ls-encrypted-data-7l9wb?fontsize=14)
```js
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](https://github.com/localForage/localForage) instance as `storage` property. This is due the fact that all getters and setters must be synchronous and [LocalForage's methods](https://github.com/localForage/localForage#callbacks-vs-promises) are asynchronous.
## Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
## Contributors β¨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/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](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
## License
The MIT License (MIT). Please see [License File](LICENSE) for more information.