N
Nuxt4w ago
yzs

is it okay to use `await useFetch()` inside my composable?

is it okay to use await useFetch() inside my composable, which is not a useFetch wrapper. i am then using my composable inside the <script setup> with await. something like this const { status, refresh, productList, totalCost } = await useMyCart()
3 Replies
kapa.ai
kapa.ai4w ago
Hi @yzs. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- No, it's generally not recommended to use await useFetch() inside your composable. This approach can lead to unexpected behavior and bugs in your Nuxt application. According to the Nuxt documentation, there are specific rules about using composables like useFetch: 1. Nuxt composables must be used synchronously - you cannot use await before calling a composable except within specific contexts like <script setup>, defineNuxtComponent, defineNuxtPlugin, or defineNuxtRouteMiddleware Nuxt Auto-imports documentation. 2. When creating custom composables that wrap useFetch or useAsyncData, you should not await them inside the composable itself. The Nuxt documentation specifically warns against this in their API documentation useFetch documentation. A Stack Overflow answer explains that this issue occurs because when you wrap useFetch within a function and await it, it breaks the reactivity chain and doesn't behave as expected Stack Overflow post. The correct approach for creating a custom composable that uses useFetch would be:
// Don't await useFetch inside the composable
function useMyCart() {
// Use useFetch without await
return useFetch('/api/cart', {
// your options here
})
}
// Don't await useFetch inside the composable
function useMyCart() {
// Use useFetch without await
return useFetch('/api/cart', {
// your options here
})
}
Then in your component:
const { status, data: productList, refresh } = await useMyCart()
const { status, data: productList, refresh } = await useMyCart()
If you need to perform additional processing on the fetched data, you can use the transform option of useFetch rather than awaiting the result inside your composable. This approach ensures that the Nuxt payload system works correctly and that reactivity is maintained throughout your application. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4w ago
<@257562536600141825> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
yzs
yzsOP4w ago
i read stack overflow answer - it gives insight on why we should not use this. maybe the docs should point this out too
useAsyncData and other composables that rely on it (useFetch in this case) return augmented promise. async function always returns native promise that doesn't affect the way it works but doesn't have data, etc from augmented promise

Did you find this page helpful?