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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With