Last active
August 8, 2025 15:16
-
-
Save alexi190/bada26c60e40589bdd452706ebd65089 to your computer and use it in GitHub Desktop.
Nuxt useFetch cache how to force refresh?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function useAPI<T>( | |
| url: string | (() => string), | |
| options: Omit<UseFetchOptions<T>, 'default'> & { default?: () => T | Ref<T> } = {}, cacheOption: { isCache: boolean, cacheTime: number } = { isCache: false, cacheTime: 60 * 5 * 1000 } | |
| ) { | |
| console.log('useAPI', url, options, cacheOption) | |
| if (cacheOption?.isCache === false) { | |
| return useFetch(() => '/api' + (typeof url === 'function' ? url() : url), { | |
| ...options, | |
| $fetch: useNuxtApp().$api | |
| }) | |
| } else { | |
| const { cacheKey, resolvedUrl } = useCacheKey(url, options.params) | |
| const cacheOptions = { | |
| key: cacheKey, | |
| transform(input: T) { | |
| const baseTransform = options.transform?.(input) || input | |
| return { | |
| ...baseTransform, | |
| fetchedAt: new Date() | |
| } | |
| }, | |
| getCachedData(key: string, nuxtApp: NuxtApp) { | |
| const data = nuxtApp.payload.data[key] || nuxtApp.static.data[key] | |
| // If data is not fetched yet | |
| if (!data) { | |
| // Fetch the first time | |
| return | |
| } | |
| // Check if data has fetchedAt timestamp | |
| if (!data.fetchedAt) { | |
| // If no timestamp, consider it expired | |
| return | |
| } | |
| // Is the data too old? | |
| const expirationDate = new Date(data.fetchedAt) | |
| expirationDate.setTime(expirationDate.getTime() + cacheOption.cacheTime) | |
| const isExpired = expirationDate.getTime() < Date.now() | |
| if (isExpired) { | |
| // Refetch the data | |
| return | |
| } | |
| return data | |
| } | |
| } | |
| return useFetch(resolvedUrl, { | |
| ...options, | |
| ...cacheOptions, | |
| $fetch: useNuxtApp().$api | |
| }) | |
| } | |
| } | |
| export function useCacheKey( | |
| url: string | (() => string), | |
| params?: MaybeRef<Record<string, any>> | |
| ) { | |
| const resolvedUrl = computed(() => '/api' + (typeof url === 'function' ? url() : url)); | |
| const paramsRef = computed(() => unref(params)); | |
| const cacheKey = computed(() => { | |
| const baseUrl = resolvedUrl.value; | |
| if (!paramsRef.value) return baseUrl; | |
| const safeParams: Record<string, string> = {}; | |
| for (const [key, value] of Object.entries(paramsRef.value)) { | |
| if (value !== undefined && value !== null) { | |
| safeParams[key] = String(value); | |
| } | |
| } | |
| const queryString = new URLSearchParams(safeParams).toString(); | |
| return queryString ? `${baseUrl}?${queryString}` : baseUrl; | |
| }); | |
| return { | |
| cacheKey, | |
| resolvedUrl | |
| }; | |
| } | |
| // calling the api how to force refresh the data. | |
| const { data, status, refresh, clear } = await useAPI<ApiResponse<ListResult<ProductCategoryName>>>('/productAttribute/category/list', { | |
| params: params, | |
| // watch: true | |
| }, { isCache: true, cacheTime: 60 * 5 * 1000 }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment