DEV Community

MedLabs
MedLabs

Posted on

using dexie and pinia in the same time

For my app I'm using Vue3, pinia for state management, and dexie as indexedDB wrapper.

my app work this way:

on Mount :

data is fetched from dexie and saved in a pinia state.
then in my component , data is rendered from the state directly...

editing data:

as I add or edit my records: my pinia action functions update data directly on dexie db, then it's refetched on the pinia state.

My question is:

is this a good solution for data management or should I get rid of pinia and only use dexie ?
does the fact that I use two data sources slow my app ?

here is an example of my pinia state:

import { defineStore, acceptHMRUpdate } from 'pinia'
import type { IPatient } from '~/db/model'
import db from '~/db/db'

export const usePatientStore = defineStore('patient', () => {
  const patients = ref<IPatient[]>([])

  // Getters

  const getPatients = computed(() => patients.value)

  const getPatientById = (id: string) => {
    const index = patients.value.findIndex((item: IPatient) => item._id === id)
    return patients.value[index]
  }
  const PatientsNames = () => {
    return patients.value.map((item: IPatient) => item.name)
  }

  const getPatientName = (id: string) => {
    if (id !== '')
      return patients.value.filter((item: IPatient) => item._id === id).map((i: IPatient) => i.name).toString()

    else return ''
  }

  // Actions
  async function fetchPatients() {
    patients.value = await db.table('patients').toArray().then(result => result.filter(el => el.deleted === false))
  }
  function addPatient(payload: IPatient) {
    db.table('patients').add(JSON.parse(JSON.stringify(payload)))
    patients.value.push(payload)
  }
  function editPatient(payload: IPatient) {
    payload.updatedAt = Date.now()
    db.table('patients').update(payload._id, JSON.parse(JSON.stringify(payload)))
    const index: number = patients.value.findIndex((item: IPatient) => item._id === payload._id)
    patients.value[index] = payload
  }
  function deletePatient(id: string) {
    db.table('patients').update(id, JSON.parse(JSON.stringify({ deleted: true, updatedAt: Date.now() })))
    const index: number = patients.value.findIndex((item: IPatient) => item._id === id)
    patients.value.splice(index, 1)
  }

  return {
    patients,
    getPatients,
    getPatientById,
    PatientsNames,
    getPatientName,
    fetchPatients,
    addPatient,
    editPatient,
    deletePatient,
  }
})

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(usePatientStore, import.meta.hot))

Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
iyadhgallah profile image
Mohamed Gallah

If you are trying to query your store, maybe you can consider using Pinia ORM to do so?