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.
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 }
})
This plugin allowed to persists the store with the indexedDB but it is no longer maintained:
It seems that this is not possible because we would have to use pinias $subscribe
method which is synchronous. So if we would use async storage options like IndexedDB, we would risk data races.
This is the reason why plugins like pinia-plugin-persistedstate only support synchronous storage options.
References:
© 2022 - 2024 — McMap. All rights reserved.