From 455044221ff617f3c3404cec1b65945a5591c988 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?No=C3=A9=20Viricel?= Date: Thu, 18 Apr 2024 17:48:56 +0200 Subject: [PATCH] feat: create custom useFetch composable #10 --- composables/useFetchWithCache.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 composables/useFetchWithCache.ts 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 +}