Storing in IndexedDB using Pinia
Asked Answered
N

3

9

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.

Narvaez answered 12/12, 2022 at 20:55 Comment(0)
G
11

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/

Gag answered 12/12, 2022 at 21:41 Comment(2)
I see. Is there any chance to use Pinia State Management with IndexedDB?Narvaez
You could implement your own plugin, updated the answerGag
U
0

This plugin allowed to persists the store with the indexedDB but it is no longer maintained:

https://github.com/iendeavor/pinia-plugin-persistedstate-2

Ulm answered 3/6, 2023 at 19:30 Comment(0)
R
0

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:

Reformism answered 16/5 at 1:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.