NuxtN
Nuxt14mo ago
Phillip

`getCachedData`: data is always undefined

In my app.vue I'm getting user data from supabase. I want to cache the values so I don't have to do it on every cache load.

I followed this YouTube tutorial by @manniL https://www.youtube.com/watch?v=aQPR0xn-MMk&t=336s&ab_channel=AlexanderLichter

But for some reason this line of code always returns undefined, causing my code to refetch and not using any cache. Why is that?:
const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
console.log('data', data) // always returns undefined



Here is my full code:
const { data: userDataAsync } = await useAsyncData('userStoreData', async () => {
    if (user.value && !isAdmin) {
        const userData = await userStore.fetchInitialData()
        console.log('userdata in useasyncdata', userData)
        return userData
    }
},
{
    watch: [user],
    getCachedData(key) {
        console.log('key', key)
        const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
        console.log('data', data)

        // refetch
        if (!data) return

        const expirationDate = new Date(data.fetchedAt)
        expirationDate.setTime(expirationDate.getTime() + 24 * 60 * 60 * 1000);
        const isExpired = expirationDate.getTime() < Date.now()

        // refetch
        if (isExpired) return

        return data
    }
})

if (userDataAsync.value) {
    userStore.setInitialData(userDataAsync.value)
}


Using Nuxt 3.12.2

Any advice is highly appreciated 🙏
YouTubeAlexander Lichter
⚡️ 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...
Was this page helpful?