Created
October 16, 2023 23:55
-
-
Save jsstoni/9d35d25515aaa1a3ba4bc79b76b76f51 to your computer and use it in GitHub Desktop.
cache fetch nuxt 3
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//usage:
const todo = await useCache('todo', 'https://URL endpoint');
//using the same data in another component
const { data } = useNuxtData('todo');