Kernel Panic
Kernel Panic
NNuxt
Created by Kernel Panic on 11/5/2024 in #❓・help
How are custom fetches used on a large scale project?
How are custom fetches used on a large scale project? I have read the custom fetch documentation on the Nuxt website. That and data-fetching. However, unless I missed something, I am struggling to put this into a large scale project. I currently have a pinia store, that uses a composable, that uses a plugin, that implements a custom fetch. While this does work to get the data, I can't seem to use useAsyncData with it, because I get an error if I try: "[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug" It's difficult to paste all of the code here because it is for my work project and client confidentiality and all that. In a nutshell, i'm trying to find a working solution where I can use a custom fetch, don't have to state the url in the page where the data is being fetched but instead it already being available a composable (eg. in the bookStore pinia store, I use an useMyApi composable which provides a fetchBooks function, which calls an endpoint using the custom fetch) An example:
<script setup lang="ts">
const { data } = await useFetch('/api/data')

async function handleFormSubmit() {
const res = await $fetch('/api/submit', {
method: 'POST',
body: {
// My form data
}
})
}
</script>
<script setup lang="ts">
const { data } = await useFetch('/api/data')

async function handleFormSubmit() {
const res = await $fetch('/api/submit', {
method: 'POST',
body: {
// My form data
}
})
}
</script>
becomes:
<script setup lang="ts">
const myStore = useMyStore();
const { data } = await myStore.fetchBooks();

async function handleFormSubmit(values) {
const res = await myStore.saveBook(values);
}
</script>
<script setup lang="ts">
const myStore = useMyStore();
const { data } = await myStore.fetchBooks();

async function handleFormSubmit(values) {
const res = await myStore.saveBook(values);
}
</script>
42 replies
NNuxt
Created by Kernel Panic on 10/18/2024 in #❓・help
Dealing with useFetch / useAsyncFetch with headers and baseUrl
I am a bit of a newbie to Nuxt. I want to create a custom fetch but with the love that comes with useFetch in terms of caching and the other bits of extras. If i use useFetch, i can load it in setup, but not as a user action. For the user action, i would need $fetch if i am understanding it correctly. I've read the documentation, created my own custom fetch. But would love to try extend the caching ability. Is this possible? I'm considering using Pinia as a "cache" but not sure if this is the right approach. Any and all tips are welcome
11 replies