Skip to content

Pinia

createPiniaPersist() (vue-storage-kit/pinia) — a Pinia plugin that persists every store's state automatically, keyed by the store's own $id by default.

ts
import { createPinia } from 'pinia'
import { createPiniaPersist } from 'vue-storage-kit/pinia'

const pinia = createPinia()
pinia.use(createPiniaPersist({ target: 'local' }))

Once installed, every store created from that pinia instance is persisted with the same options — there's no per-store configuration; scope a separate pinia.use() call (or a second Pinia instance) if different stores need different target/pick/omit.

Options

key

string · default: the store's own $id

Storage key to persist under.

target

StorageTarget · default: 'local'

pick

string[]

Persist only these state keys. Mutually exclusive with omit — if both are set, pick wins.

omit

string[]

Persist every state key except these.

serializer

Serializer<unknown> · default: JSON serializer

beforeRestore

(ctx: PiniaPluginContext) => void

Called right before a restored value is applied to the store's state.

afterRestore

(ctx: PiniaPluginContext) => void

Called right after a restored value is applied.

onError

(err: StorageError) => void

Called on a read/write/parse failure instead of throwing.

Example

ts
import { createPinia, defineStore } from 'pinia'
import { createPiniaPersist } from 'vue-storage-kit/pinia'

const pinia = createPinia()
pinia.use(
  createPiniaPersist({
    target: 'local',
    omit: ['transientUiFlag'],
    onError: (err) => console.error('Persist failed:', err),
  }),
)

const useSettings = defineStore('settings', {
  state: () => ({ theme: 'light', transientUiFlag: false }),
})

// Reading/writing `theme` on this store now round-trips through
// localStorage under the key "settings" automatically.

Restore runs asynchronously (the adapter may be backed by IndexedDB) — a mutation made in the same synchronous turn as the store's creation is never silently reverted by a slower-resolving restore, so it's safe to set initial overrides immediately after creating a store.