diff --git a/composables/useFetchWithCache.ts b/composables/useFetchWithCache.ts new file mode 100644 index 0000000..1f81e58 --- /dev/null +++ b/composables/useFetchWithCache.ts @@ -0,0 +1,19 @@ +export default async (key: string, url: string, opts?: object): Promise> => { + const { data: cached } = useNuxtData(key) + + if (!cached.value) { + const { data, error } = await useFetch(url, opts) + + if (error.value) { + throw createError({ + ...error.value, + message: `Could not fetch data from ${url}`, + }) + } + + // Update the cache + cached.value = data.value as T + } + + return cached as Ref +}