NuxtN
Nuxt8mo ago
26 replies
lazygopher

Fetching data in Pinia store - useFetch make sense here?

I have Nuxt app with Pinia. In one store, I find myself using useFetch for data fetching (with SSR support), then expose the status, error and another computed variable which does some computation on the data returned.
# stores/store-a.ts
export const useStoreA = defineStore("storeA", () => {
  const {
   data,
   status,
   error,
   refresh,
  } = useFetch<Items[]>("/api/items", { lazy: true })

  const myItems: Ref<Item[]> = computed(() => {
   const itemData = data.value || []
   .. some more logic ..
   return itemData
  })

  return {
   data,
   status,
   error,
   refresh,
  }
})

This provides pretty damn clean API, with status and error baked in.

But when I looked for examples of Pinia with useFetch, I couldn't find any. All the AI GTPs suggest exposing a function to fetch data (e.g, fetchItems()), while using $fetch.

Am I missing something here? Any reason to not useFetch on store setup?
Was this page helpful?