NuxtN
Nuxt10mo ago
4 replies
kozy

useAsyncData with pinia

I was reading through the documentation on useAsyncData and I noticed that it mentioned:
useAsyncData is for fetching and caching data, not triggering side effects like calling Pinia actions, as this can cause unintended behavior such as repeated executions with nullish values. If you need to trigger side effects, use the callOnce utility to do so.
with the following example:
const offersStore = useOffersStore()

// you can't do this
await useAsyncData(() => offersStore.getOffer(route.params.slug))


I'm curious if you could provide more explanation on this... Specifically, if the presence of a key/or a single fetch without any computed url changes things.
In my case, I don't want to the call to block the route e.g.,
const userStore = useUserStore()

await useAsyncData('offers', store.getUser, {
  lazy: true
})

I'm aware I could move the logic out of the store and leverage the built-in cache from
useFetch
/ useAsyncData.
Would something like this work as well?
const useUserStore = defineStore('use', () => {
  const user = ref<User>()

  function fetchUser() {
    // useFetch instead of $fetch
    const { data } = useFetch('', { lazy: true })
    user.value = data.value
  }
})

// script setup
await callOnce(async () => {
  await store.fetchUser()
})
Nuxt
Nuxt provides composables to handle data fetching within your application.
Data Fetching · Get Started with Nuxt
Was this page helpful?