pinia-plugin-keep
TypeScript icon, indicating that this package has built-in type declarations

0.3.1Β β€’Β PublicΒ β€’Β Published

pinia-plugin-keep

NPM version

🍍🍍 Not only a pinia plugin.

Description

  • keepPiniaPlugin

Persistence your state to localStorage.

You only need to install the keepPiniaPlugin in main.ts, like the above Usage. And the plugin will keep your state in the localStorage when you use the store.

The default config is persistence the state to localStorage. You could change the config in the keepPiniaPlugin function, like the following:

pinia.use(_ => keepPiniaPlugin(_, 'session'))

So, the state will be kept in the sessionStorage.

  • resetPluginPinia

Resets the store to its initial state with a nested value pass the keypath as the argument.

When you install this plugin, your store will register a function call $resetPath, and you could use it to reset the value with state initial.

TIPS: $resetPath is options api only

For example:

  • userStore.ts
import { defineStore } from 'pinia'

export const useUserStore = defineStore({
  id: 'user',
  state: () => {
    return {
      token: '',
      userInfo: {
        age: 18,
        name: 'cx33'
      }
    }
  },
  // getters
  // ...
  // actions
  // ...
})
  • anywhere
import useUserStore from './userStore'

const store = useUserStore()

store.$resetPath('userInfo.age') // <- here is equal to store.$state.userInfo.age = 18

Install

npm i pinia-plugin-keep

Usage

  • main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
// ↓ import the plugin
import { keepPiniaPlugin, resetPluginPinia } from 'pinia-plugin-keep' 

import App from './App.vue'

const app = createApp(App)
const pinia = createPinia()

pinia.use(keepPiniaPlugin) // <- use the plugin
pinia.use(resetPluginPinia) // <- use the plugin

app.use(pinia)

app.mount('#app')

TypeScript

When adding new properties to stores, you should also extend the PiniaCustomProperties interface.

You need to create a file like pinia.d.ts in your project. And add the following code:

import 'pinia'

declare module 'pinia' {
  export interface PiniaCustomProperties {
    $resetPath: (path: string) => void
  }
}

License

MIT License Β© 2022 JiatLn

Package Sidebar

Install

npm i pinia-plugin-keep

Weekly Downloads

1

Version

0.3.1

License

MIT

Unpacked Size

12.3 kB

Total Files

6

Last publish

Collaborators

  • jiatln