Created
January 29, 2025 00:19
-
-
Save MuhammadKhizar7/488ab69fa584598f64d3106510a61f64 to your computer and use it in GitHub Desktop.
useFatchWithCached.ts
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
import { StorageSerializers } from '@vueuse/core'; | |
export default async <T>(url: string) => { | |
// Use sessionStorage to cache the lesson data | |
const cached = useSessionStorage<T>(url, null, { | |
// By passing null as default it can't automatically | |
// determine which serializer to use | |
serializer: StorageSerializers.object, | |
}); | |
if (!cached.value) { | |
const { data, error } = await useFetch<T>(url, { | |
headers: useRequestHeaders(['cookie']), | |
}); | |
if (error.value) { | |
throw createError({ | |
...error.value, | |
statusMessage: `Could not fetch data from ${url}`, | |
}); | |
} | |
cached.value = data.value as T; | |
} else { | |
console.log(`Getting value from cache for ${url}`); | |
} | |
return cached; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment