All Projects → prazdevs → pinia-plugin-persistedstate

prazdevs / pinia-plugin-persistedstate

Licence: MIT License
🍍 Configurable persistence and rehydration of Pinia stores.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to pinia-plugin-persistedstate

nuxt3-app
Nuxt3 (Nuxt 3) best starter repo, Tailwindcss, Sass, Headless UI, Vue, Pinia, Vite
Stars: ✭ 252 (+88.06%)
Mutual labels:  pinia
vite-primevue-starter
VUE 3 Starter project for using primevue 3 with Vite 2 - Pages, Layouts, Validation
Stars: ✭ 37 (-72.39%)
Mutual labels:  pinia
vue3-ts-vite-ssr-starter
Use vue3 vite2 typescript eslint SSR pinia unocss vue-router element-plus scss
Stars: ✭ 114 (-14.93%)
Mutual labels:  pinia
vue-admin-work-x
🎉🎉🎉Vue Admin Work X,漂亮、强大、完善。采用 Vue3 Webpack Typescript Element Plus编写的中后台框架。全面的系统配置,优质模板,常用组件,真正一站式开箱即用🎉🎉🎉
Stars: ✭ 151 (+12.69%)
Mutual labels:  pinia
mall-admin-web
youlai-mall 管理前端,基于vue-element-admin升级的Vue3版本,技术栈:Vue3 + Vite2+ TypeScript + Element-Plus +Pinia。
Stars: ✭ 230 (+71.64%)
Mutual labels:  pinia
taro3-vue3-template
一个基于 Taro3 和 Vue3 框架微信小程序模版。 核心技术采用Taro3、Vue3、TypeScript、NutUi、Vux4/Pinia、VueUse
Stars: ✭ 115 (-14.18%)
Mutual labels:  pinia
tdesign-vue-next-starter
A starter-kit for TDesign Vue Next UI components
Stars: ✭ 283 (+111.19%)
Mutual labels:  pinia
iro
IRO - Amazing Color Tools. Color Convert HEX, RGB, HSL and CMYK. Color Inspection with Camera.
Stars: ✭ 103 (-23.13%)
Mutual labels:  pinia
vue-lite-admin
a lite vue3.0 admin template,there is no typescript and vuex (但注释挺全)
Stars: ✭ 67 (-50%)
Mutual labels:  pinia
admin-work
Vue3 和 NaiveUI 的完美结合—Admin Work,拥有漂亮、强大、完善的功能。采用 Vue3 Vite2 Typescript NaiveUI Pinia编写的中后台框架。全面的系统配置,优质模板,常用组件,真正一站式开箱即用。持续更新,不断完善,一直在前进~~
Stars: ✭ 394 (+194.03%)
Mutual labels:  pinia
example-nuxt-3
Example using Nuxt 3
Stars: ✭ 54 (-59.7%)
Mutual labels:  pinia
Admin-Frame-Vue3
基于Vue3 + Element-Plus + Vite 开发的中/后台管理系统
Stars: ✭ 181 (+35.07%)
Mutual labels:  pinia
artemis
MateCloud前端代码,基于vue3、vite、pinia、ant-design vue实现的中台系统
Stars: ✭ 129 (-3.73%)
Mutual labels:  pinia
insta-share
Instant File Sharing powered by IPFS Networks. Build with Vue 3 and ViteJS
Stars: ✭ 53 (-60.45%)
Mutual labels:  pinia
Surmon.me
🆒 My personal website and blog, powered by @vuejs (3)
Stars: ✭ 1,767 (+1218.66%)
Mutual labels:  pinia
pinia-shared-state
🍍 A lightweight plugin to sync your pinia state across browser tabs.
Stars: ✭ 51 (-61.94%)
Mutual labels:  pinia

Artwork from Pinia

pinia-plugin-persistedstate

Configurable persistence and rehydration of Pinia stores.

npm CI Coverage Maintainability License

Features

  • Persist Pinia stores with the same API as vuex-persistedstate (and more).
  • Configurable per Pinia store.
  • Still compatible with Vue 2 and 3.
  • No external dependencies.
  • Supports a custom serializer for advanced needs.
  • Super small (<1kB).

⚙️ Installing

  1. Install with your favorite package manager:

    • pnpm : pnpm i pinia-plugin-persistedstate
    • npm : npm i pinia-plugin-persistedstate
    • yarn : yarn add pinia-plugin-persistedstate
  2. Add the plugin to pinia:

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

🚀 Usage

You just need to add the persist option to the store you want to be persisted as follows:

import { defineStore } from 'pinia'

//* using option store syntax
export const useStore = defineStore('main', {
  state: () => {
    return {
      someState: 'hello pinia',
    }
  },
  persist: true,
})

//* or using setup store syntax
export const useStore = defineStore(
  'main',
  () => {
    const someState = ref('hello pinia')
    return { someState }
  },
  {
    persist: true,
  },
)

In case you want to configure how the data should be persisted, persist can take options:

  • key: string : Key to use in storage (defaults to the current store id).
  • storage : Storage like object to persist state to. Must have getItem and setItem methods (defaults to localStorage).
  • paths: Array<string> : Array of dot-notation paths to partially persist the state, [] means no state is persisted (defaults to undefined and persists the whole state).
  • beforeRestore: (context) => void : Hook executed (if set) before restoring the state from local storage.
  • afterRestore: (context) => void : Hook executed (if set) after restoring the state from local storage.

The context passed to the hooks is the PiniaPluginContext. It exposes properties such as the current store. More infos here.

  • serializer: { serialize, deserialize } : Custom serializer/deserializer :
    • serialize: (state) => string : Function to serialize the state before storing (defaults to JSON.stringify).
    • deserialize: (string) => state : Function to deserialize the stored stated before rehydrating (defaults to JSON.parse).

The state used in serialize and deserialize is the generic state of the current store. More infos here.

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  state: () => {
    return {
      someState: 'hello pinia',
      nested: {
        data: 'nested pinia',
      },
    }
  },
  persist: {
    key: 'store-key',
    storage: window.sessionStorage,
    paths: ['nested.data'],
    beforeRestore: context => {
      console.log('Before hydration...')
    },
    afterRestore: context => {
      console.log('After hydration...')
    },
  },
})

The config above will only persist the nested.data property in sessionStorage under store-key.

It will also execute the beforeRestore and afterRestore hooks respectively before and after hydration.

Usage with Nuxt

Declare a Nuxt Plugin to add the plugin to Pinia.

import { createNuxtPersistedState } from 'pinia-plugin-persistedstate'
import { defineNuxtPlugin, useCookie } from '#app'

export default defineNuxtPlugin(nuxtApp => {
  nuxtApp.$pinia.use(createNuxtPersistedState(useCookie))
})

The plugin will use Nuxt's Cookies and useCookie to define a storage to persist your stores with SSR.

import { defineStore } from 'pinia'

export const useUserStore = defineStore('ssr', {
  persist: true
})

Warning: when using createNuxtPersistedState, overriding the storage option in the store definition will break server-side persistance/rehydration with Cookies.

🔧 Factory function configuration

Need to override default options? You can import and use createPersistedState(options):

import { createPinia } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(createPersistedState({
  storage: sessionStorage,
  beforeRestore: () => {},
  afterRestore: () => {},
  serializer: {
    serialize: JSON.stringify,
    deserialize: JSON.parse,
  }
}))

The options passed will be used in any store declaring persist: true. You can still override these defaults with per-store options.

You can also override default options in Nuxt with createNuxtPersistedState(useCookie, options).

⚠️ Limitations

References do not persist

Beware of the following:

const a = {
  1: 'one',
  2: 'two',
  ...
}
const b = a

// Before hydration 'a' and 'b'
// point to the same object:
a === b -> true

// After hydration (page reload)
// 'a' and 'b' are different objects
// with the same content:
a === b -> false

As a consequence, reactivity between a and b is lost.

To get around this you can exclude either a or b from persisting and use the afterRestore hook to populate them after hydration. That way a and b have the same reference again and reactivity is restored after page reload.

Non primitive types are not persisted

Due to serialization (JSON.stringify/JSON.parse) needed to persist in storage, non primitive typed data such as Date are no rehydrated as Date but as string instead.

To get around this you can use the afterRestore hook to reformat the data as needed.

Storage must be synchronous

When providing a storage option, all methods (getItem, setItem) must be synchronous. This is due to Pinia's state subscription ($subscribe) being synchronous (like mutations).

If you want to add asynchronous behavior (such as async storages), you can try subscribing to actions ($onAction). Actions are made for asynchronous tasks and provide proper error handling.

🤝 Contributing

This project tries to bring vuex-persistedstate's API to Pinia but I did not bring the whole API yet.

Run into a problem? Open an issue. Want to add some feature? PRs are welcome!

👤 About the author

Feel free to contact me:

  • twitter: @prazdevs
  • discord: PraZ#4184"

📝 License

Copyright © 2022 Sacha Bouillez.
This project is under MIT license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].