Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing in IndexedDB using Pinia

Is it possible to store data locally in IndexedDB using Pinia ?

I tried using Pinia persisted state and it stores data locally in LocalStorage as default. I just want to try if it will work with IndexedDB since it has a larger size capacity.

like image 707
ayaayharvey Avatar asked Apr 26 '26 03:04

ayaayharvey


1 Answers

You can implement your own pinia plugin to use whatever storage you want. Here is an example using localForage.

import { createApp } from 'vue'
import { createPinia, type Store } from 'pinia'
import App from './App.vue'
import localForage from "localforage";

const app = createApp(App)

async function indexDbPlugin({ store }: { store: Store }) {
    const stored = await localForage.getItem(store.$id + '-state')
    if (stored) {
        store.$patch(stored)
    }
    store.$subscribe(() => {
        localForage
            .setItem(store.$id + '-state', { ...store.$state }) // Destructure to transform to plain object
    })
}

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

app.use(pinia)
app.mount('#app')

https://pinia.vuejs.org/core-concepts/plugins.html#introduction

pinia-plugin-persistedstate does not support asynchronous storage

Another way would be to use useStorage from VueUse to better choose what you want to persist.

import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useStorage, useStorageAsync, type StorageLikeAsync } from '@vueuse/core'
import localforage from 'localforage'

export const useUserStore = defineStore('user', () => {
  const name = useStorageAsync('name', 'Hello', localforage as StorageLikeAsync) // persist to localforage
  const age = useStorage('age', 18) // persist to localStorage
  const id = ref(0) // not persisted
  return { name, age, id }
})

https://vueuse.org/core/useStorage/

like image 125
Pierre Said Avatar answered Apr 28 '26 17:04

Pierre Said