코드/Nuxt3

[Nuxt] getCachedData 사용하기

Yeah-Panda 2025. 1. 13. 10:49

useFetch, useAsyncData 에서 url 베이스 혹은 key를 사용하여 캐시 처리를 하는 방법외에 캐시를 다루는 방법이 있습니다.

`getCachedData` 를 사용하는 것입니다.

const { data } = await useFetch(`/api/random-user`, {
  getCachedData(key, nuxtApp) {
      const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key];
      return data;
  },
});

 

getCachedData 는 두 가지의 매개변수가 삽입되는 함수 입니다.

https://nuxt.com/docs/api/composables/use-async-data#params

 

useAsyncData · Nuxt Composables

useAsyncData provides access to data that resolves asynchronously in an SSR-friendly composable.

nuxt.com

https://nuxt.com/docs/api/composables/use-fetch#params

 

useFetch · Nuxt Composables

Fetch data from an API endpoint with an SSR-friendly composable.

nuxt.com

 

  • key: 캐시 키
  • nuxtApp:  nuxt app instance 입니다.

nuxtApp 의 속성중 payload 가 있습니다.

일부 메타데이터와 함께 useFetch, useAsyncData 를 사용하여 application 에서 수행된 모든 요청에 대해 서버에서 호출된 응답을 클라이언트로 전달되는 데이터입니다.

payload의 data 속성중 key 로 선언된 캐시가 있다면 캐시를 사용합니다.

그렇지 않다면 undefined 가 반환되며 캐시를 사용하지 않는다는 의미 입니다.

그 뒤의 nuxtApp.static.data[key] 는 generate site render 모드 혹은 static 데이터를 사용할때 사용됩니다. 

 

하지만 우리는 getCachedData 를 사용하는 경우에도 만료 시점을 설정할수 있어야합니다.

transform 을 사용합니다.

const { data } = await useFetch(`/api/random-user`, {
  transform(data) {
    return {
      ...data,
      expiresAt: Date.now() + 10_000
    }
  },
  getCachedData(key, nuxtApp) {
    const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key];
    if (data?.expiresAt >= Date.now()) {
      return data;
    } else {
      return undefined;
    }
  },
});

transfom 함수는 useFetch 를 통한 응답을 매개변수로 받습니다.

그 data 의 값에 캐시 만료 시점을 추가합니다. (expireAt)

 

위 코드중 10_000 은 10000 을 의미합니다. 가독성을 올리기위한 자바스크립트 리터럴 표현식입니다.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#literals

 

Lexical grammar - JavaScript | MDN

This page describes JavaScript's lexical grammar. JavaScript source text is just a sequence of characters — in order for the interpreter to understand it, the string has to be parsed to a more structured representation. The initial step of parsing is cal

developer.mozilla.org

숫자 리터럴에 밑줄(_)을 사용하는 표기법은 ECMAScript 2018 (ES9) 버전부터 도입되었습니다.

 

그후 getCachedData 에서 data 의 expiresAt 의 시점을 비교하여 cached 된 데이터를 리턴하거나 undefined (캐시 비사용) 를 반환할수 있습니다.