Skip to content

Instantly share code, notes, and snippets.

@jsstoni
Created October 16, 2023 23:55
Show Gist options
  • Save jsstoni/9d35d25515aaa1a3ba4bc79b76b76f51 to your computer and use it in GitHub Desktop.
Save jsstoni/9d35d25515aaa1a3ba4bc79b76b76f51 to your computer and use it in GitHub Desktop.
cache fetch nuxt 3
export default async function (key, endpoint, options = {}) {
const cache = ref();
const { data: cachedData } = useNuxtData(key);
if (cachedData.value) {
cache.value = cachedData.value;
} else {
const { data, error } = await useLazyAsyncData(
key,
() => $fetch(endpoint),
options
);
if (error.value) {
throw createError({ statusCode: 404, statusMessage: "Page Not Found" });
}
cache.value = data.value;
}
return cachedData;
}
@jsstoni
Copy link
Author

jsstoni commented Oct 16, 2023

//usage:

const todo = await useCache('todo', 'https://URL endpoint');

//using the same data in another component
const { data } = useNuxtData('todo');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment