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
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:
Then in your component:
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:
----------------------<@257562536600141825> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
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