unjs / unstorage

💾 Unstorage provides an async Key-Value storage API with conventional features like multi driver mounting, watching and working with metadata, dozens of built-in drivers and a tiny core.
https://unstorage.unjs.io
MIT License
1.75k stars 132 forks source link

How to access all available stores #452

Open Rednas83 opened 3 months ago

Rednas83 commented 3 months ago

Something like var stores = await useStorage.getItems() // Returns [store1: {value1: value}] or to just get the store names var stores = await useStorage.getItemsByName() // Returns [store1]

Similar to what is possible with pinia

import { getActivePinia } from "pinia"
var stores = getActivePinia() // Returns [store1: {value1: value}]
Rednas83 commented 3 months ago

Sorry, looks like there is already support for it image

Another question. How can you declare a universal store that can be accessed everywhere?

Tried something like plugins/storage.ts

import { createStorage } from "unstorage"
export default defineNuxtPlugin(() => {
  const storage = createStorage()
  return {
    provide: {
      storage: storage,
    },
  }
})

But it returns an error when destructed with const { $storage } = useNuxtApp() image Also I am getting sometimes image

Tried:

restarting dev server
pnpm nuxt cleanup
pnpm nuxt typecheck -> No errors
restarting vscode
experimental: {  asyncContext: true } in nuxt.config.ts

For pinia its something like: stores\useLogStore.ts

export const useLogStore = defineStore("log", () => {
  const values = ref([] as log[])

  function $reset() {
    values.value = []
  }

  return { values, $reset }
})
Rednas83 commented 3 months ago

Succesfully migrated pinia to unStorage🥳.

Fixed it by applying any to useNuxtApp() and moving it inside the composables

export async function save(iContent: string, iValue?: any) {
  const { $storage } = useNuxtApp() as any

Not ideal, but it works for now. Please let me know if there is a better solution

Rednas83 commented 3 months ago

Also I would like to create some shortcuts for easier access.

Something like plugins/storage.ts

  return {
    provide: {
      init: init,
      storage: storage,
      codes: ref(await storage.getItem("codes")), // TODO shortcuts
      settings: ref(await storage.getItem("settings")), // TODO shortcuts
      motors: ref(await storage.getItem("motors")), // TODO shortcuts
      chart: ref(await storage.getItem("codes")), // TODO shortcuts
    },
  }

app.vue const { $codes, settings, motors, chart } = useNuxtApp()

Is something like that possible?