Skip to content

JiatLn/pinia-plugin-keep

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

24 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

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

About

๐Ÿ Not only a pinia plugin.

Resources

License

Stars

Watchers

Forks

Packages

No packages published