NuxtN
Nuxt10mo ago
12 replies
zangetsu

Nuxt 3.16.1 - getCachedData not working (?)

Hi,
I was watching a video by Alexander Lichter about caching API calls in Nuxt and decided to test this approach in my Nuxt app.

I copied and pasted the code exactly as shown:

const { data } = await useFetch<any>('https://icanhazdadjoke.com/', {
  headers: {
    Accept: 'application/json',
  },
  transform(input) {
    return {
      ...input,
      fetchedAt: new Date(),
    }
  },
  getCachedData(key) {
    const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
    // If data is not fetched yet
    if (!data) {
      // Fetch the first time
      return
    }

    // Is the data too old?
    const expirationDate = new Date(data.fetchedAt)
    expirationDate.setTime(expirationDate.getTime() + 10 * 1000)
    const isExpired = expirationDate.getTime() < Date.now()
    if (isExpired) {
      // Refetch the data
      return
    }

    return data
  },
})


However, when I debug nuxtApp.payload.data or nuxtApp.static.data[key], even if the API has been called 40 times, Nuxt doesn't save the data.

I even added this to my nuxt.config:

export default defineNuxtConfig({
  experimental: {
    payloadExtraction: true,
  },
}
Was this page helpful?