N
Nuxt3w 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
const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
console.log('data', data) // always returns undefined
Here is my full code:
constdata: 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)
}
constdata: 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 🙏
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...
4 Replies
kapa.ai
kapa.ai3w ago
Hi @Phillip. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Based on the information provided in the knowledge sources, I can offer some insights into your issue with getCachedData in Nuxt 3.12.2. The problem you're experiencing where data is always undefined could be due to a few reasons: 1. Payload structure: The nuxtApp.payload.data**key] or nuxtApp.static.data[key] might not contain the data you expect. In Nuxt 3, the payload structure has changed compared to earlier versions. According to the [useNuxtApp documentation (https://nuxt.com/docs/api/composables/use-nuxt-app#payload), the payload.data object contains data fetched from API endpoints using useFetch or useAsyncData. 2. Key mismatch: Ensure that the key you're using in getCachedData matches the key used when initially fetching the data. In your code, you're using 'userStoreData' as the key for useAsyncData. Make sure this key is consistent. 3. Server-side rendering: If the data is not being fetched on the server side, it won't be available in the payload on initial client-side render. As mentioned in the data fetching documentation (https://nuxt.com/docs/getting-started/data-fetching#suspense), if you haven't fetched data on the server (e.g., with server: false), the data won't be fetched until hydration completes. 4. Caching mechanism: The getCachedData function you're using is based on the example from the YouTube tutorial, but it's important to note that this is a custom implementation and not a built-in Nuxt feature. The actual caching mechanism might need adjustments to work correctly in your specific use case. To troubleshoot this issue, you could try the following: 1. Log the entire nuxtApp.payload and nuxtApp.static objects to see their structure and contents. 2. Ensure that your data is being fetched on the server side if you want it to be available in the payload. 3. Consider using useNuxtData to access cached data, as shown in the useNuxtData documentation** (https://nuxt.com/docs/api/composables/use-nuxt-data). This is a built-in Nuxt composable for accessing cached data. 4. If you're using a custom caching mechanism, make sure it's properly integrated with Nuxt's data fetching lifecycle. If these steps don't resolve the issue, you might want to consider simplifying your approach or using Nuxt's built-in caching mechanisms instead of a custom implementation. Remember that the behavior of data fetching and caching can be complex, especially when dealing with server-side rendering and client-side hydration. If you continue to face issues, you might want to create a minimal reproducible example and seek help from the Nuxt community or official support channels. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3w ago
<@728986061098713110> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Phillip
PhillipOP3w ago
I noticed that when changing tabs it doesn't even get in the getCachedData function and immediately refetches
Phillip
PhillipOP3w ago
I used this workaround mentioned here https://github.com/nuxt/nuxt/issues/24332#issuecomment-2238821604 and this is now working.
constdata: userDataAsync } = await useAsyncData('userStoreData', async () => {
if (user.value && !isAdmin) {
const cachedData = nuxtApp.payload.data['userStoreData'] || nuxtApp.static.data['userStoreData'] as UserDataWithFetchedAt


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

if (!isExpired) return cachedData
}

const userData = await userStore.fetchInitialData()
return userData
}
},
{
watch: [user],
transform(data) {
return { ...data, fetchedAt: Date.now() }
},
// getCachedData(key) {
// console.log('key', key)
// console.log('nuxtApp.payload', nuxtApp.payload.data['userStoreData'])
// 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
// }
})
constdata: userDataAsync } = await useAsyncData('userStoreData', async () => {
if (user.value && !isAdmin) {
const cachedData = nuxtApp.payload.data['userStoreData'] || nuxtApp.static.data['userStoreData'] as UserDataWithFetchedAt


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

if (!isExpired) return cachedData
}

const userData = await userStore.fetchInitialData()
return userData
}
},
{
watch: [user],
transform(data) {
return { ...data, fetchedAt: Date.now() }
},
// getCachedData(key) {
// console.log('key', key)
// console.log('nuxtApp.payload', nuxtApp.payload.data['userStoreData'])
// 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
// }
})
GitHub
Re-use getCachedData when refreshing asyncData · Issue #24332...
Describe the feature Hey 👋🏻 With the introduction of getCachedData, useFetch and useAsyncData have an elegant way to re-use existing data easily. There is a downside though, as @broox mentioned in ...
Want results from more Discord servers?
Add your server