Skip to content

Commit

Permalink
feat: create custom useFetch composable #10
Browse files Browse the repository at this point in the history
  • Loading branch information
wazolab committed Apr 18, 2024
1 parent 6b8f363 commit 4550442
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions composables/useFetchWithCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export default async <T>(key: string, url: string, opts?: object): Promise<Ref<T>> => {
const { data: cached } = useNuxtData<T>(key)

if (!cached.value) {
const { data, error } = await useFetch<T>(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<T>
}

0 comments on commit 4550442

Please sign in to comment.