Shareable custom useAsyncData composable
I have a composable that fetches data with
useAsyncData
. I would like to reuse this composable in other components. So that would look something like this:
If I understand correctly, useAsyncData should memoize it's value. So, I expected that the fetching data inside useAsyncData
would only be called once. However, this doesn't seem to be the case and the fetching data gets called twice.
Am I missing something here? I understand that I could get the cached value with useNuxtData
inside the second component. But Ideally I would have one composable that's smart enough to either fetch the data or retrieve it from the cache.
I have a Codesandbox with a POC here to show what I'm exactly trying to do5 Replies
I found this video quite helpful, when implementing something similar https://www.youtube.com/watch?v=aQPR0xn-MMk
TLDW: Use
getCachedData
on useAsyncData
Alexander Lichter
YouTube
Nuxt 3.8 - Client-side caching with getCachedData ✨
⚡️ Nuxt 3.8 was released just a day ago, packed with lots of amazing features. Among the updates, one change for
useFetch
and useAsyncData
is pretty significant IMO - getCachedData
. In this video, we will explore how that function can avoid superfluous calls to an API and cache data for visitors on the client, either until a hard-reload or...Thank you! That's actually a cool approach. I created an updated Codesandbox that does this which seems to work well.
However, looking at the docs the Nuxt docs for useAsyncData. It seems like the default value for
getCachedData
is key => nuxt.isHydrating ? nuxt.payload.data[key] : nuxt.static.data[key]
. Why would they only set the payload data when hydrating?
For me it seems like nuxt.static.data
is always empty...I'm not sure. It says it only caches when
payloadExtraction
is enabled, so maybe something to do with thatOke makes sense. Thanks for your help!
You're welcome 🙂