~/dejafu/blog/getcacheddata
Created a day ago
Last changed a day ago

Nuxt - getCachedData

In certain scenarios, I find Nuxt's caching functionality very useful. However, it is not explained in detail in the documentation - at least not in written form. There is a very good explanation about this from Alexander Lichter that I recommend watching.

For example, recently I had to implement data fetching for search tags and so-called NACE codes when building a search text box. When users click on the tags and NACE codes filter, the async data should be fetched.

However, when inspecting the logs, we discovered this data was being fetched every time a user clicked on the filter, which was inefficient. The Nuxt function getCachedData, which can be defined inside the useAsyncData composable, solves this problem.

How to use getCachedData

To make use of getCachedData the function has to be implemented like that:

<script setup lang="ts">
const nuxtApp = useNuxtApp();

// useAsyncData with caching enabled
const { data: tags } = await useAsyncData(
  "tags", // Unique key for caching
  () =>
    $fetch("https://fakeApi.com/tags"),
  {
    
    // Custom function to determine if cached data should be used
    getCachedData(key) {
      // Try to get data from Nuxt's payload or static data
      const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key];
      
      // If data doesn't exist, skip cache and fetch fresh data
      if (!data) {
        return;
      }

      // Data exists in cache, return it instead of fetching
      return data;
    },
  }
);
</script>

<template>
  <div>
    <h1>Index page</h1>
    {{ data.tags }}
    <NuxtLink to="/about">To the about page</NuxtLink>
  </div>
</template>

Essentially, we check whether data exists in Nuxt's payload or static data. If the data is already available on the client, we reuse it; otherwise, we fetch fresh data from the server. In our use case, the tags data doesn't change, so fetching it once during application load is sufficient.

Without getCachedData, the application would refetch this data every time a user clicked the filter.

Refreshing the cache

If the cache content changes over time, you can implement some kind of logic to determine when to refetch the data.

There is an example given by Alexander Lichter in a GitHub repository. It is mentioned in the video above that the example is provided for explanational purposes only, as the real implementation depends on your project's circumstances, but I think it does a good job doing so. I will show another example in a future blog post using Server-Sent Events in PocketBase, so stay tuned if you would like to know more about this.

Thanks for checking in. See you next time!

~ jacky