N
Nuxt7d ago
maroo

Is it safe to use useFetch() inside a function?

Is it unsafe to use useFetch() inside a function? After making a POST request, the request repeats every time the reactive variable ref() is changed within the page. Could this be a bug? Please refer to the minimal example: https://codesandbox.io/p/devbox/h4cqq2?file=%2Fapp.vue%3A28%2C9
4 Replies
Cue
Cue7d ago
Alexander Lichter
YouTube
You are using useFetch WRONG! (I hope you don't)
💪🏻 useFetch is a mighty composable to fetch data in your Nuxt.js application. It can do so many things, from updating state to refreshing calls easily and even data caching is possible. But often I see that people misuse useFetch because it is so tempting to use all the features, even when you shouldn't. In this video I show the most common mist...
Cake
Cake7d ago
why do you want to useFetch inside the function? in ur code is it a custom useFetch wrapper? or because you perhaps want the loading state to be handled automatically?
maroo
maroo7d ago
The information presented in the video is absolutely correct. However, I believe that consistently using useFetch for all data fetching and posting would enhance readability and improve error handling. As you may know, when using $fetch, it becomes difficult to perform early returns when handling errors with the .catch() chain, often leading to a larger try...catch. When wrapped in a catch, it’s harder to specifically detect and handle other errors, requiring the import and casting of types like IFetchError for more accurate error handling. I think useFetch, while being a macro, is named like a composable that can be used anywhere within the setup context. Since the official documentation doesn’t emphasize important caveats, it’s an easy trap to fall into.
Cue
Cue7d ago
Yes, that’s precisely how it is designed to be used as per the documentation. The documentation does state the significant differences between useFetch, $fetch and useAsyncData. It is true, many people have fallen foul of its correct usage which is why resources such as Alex’s video exist. But over time the docs on this topic have been improved. Lest we forget, there is no example portrayed in the documentation in a manner in which it shouldn’t be used.
Want results from more Discord servers?
Add your server