Not guilty yet, I'm building a big nuxt 3 spa and mutation of data is just on my list. So this comes in handy. For now I'm only getting and based on url change, which I made a computed for, or query change, which is relying on pinia state, I refetch the data using useFetch reactivity. In one or two cases I use immediate false and execute useFetch from a watch, which works great as well. Submitting data is something I will start with just this week, so I will keep this $fetch pattern in mind. In onSubmit I then can collect formData and post it, when form validity is correct of course. It's luck so far, didn't know composables could lead me into this kind of trouble. Only top level, Tarabass, only top level. Will help with code review as well! Thx
I think I am guilty yeah, I have the following in my pinia store: const getDeck = async (id: string) => { const { data } = await useFetch(`/api/decks/:${id}`, { method: "GET", headers: useRequestHeaders(["cookie"]), }) deck.value = data.value } Perhaps this should be using $fetch and then wrapping the call to getDeck in an useAsyncData on the component/page ?
@Tarabass Perfect timing then 🙊 Yeah, using composables not in the vue context (but in "event handlers", watchers etc. etc.) can really cause trouble 🙈 You are welcome 🙌🏻
I cannot emphasize on how good this video was. I personally want to switch from the vue to nuxt, and these videos are clear and helpful. Thanks Alexander !
Perfect timing for this video! Thank you so much. I just stumpled upon a video of yours over on the vue school channel and then saw this video on your channel. I started developing an app using nuxt a few weeks ago and am at the point where it is starting to become more complex. I was really struggling with the API and with useFetch - your video made me realize that I don't need useFetch for what I am doing and that I am better off just using $fetch.
Thanks Alex! I'm so new to Nuxt that I haven't even fallen for this trap yet lol (building a thing as I learn 🤓). I appreciate the info, and best wishes!
love the videos, especially how concise they are. I was curious if you ever considered posting these pieces in text format (either on a blog or a twitter thread)
Interestingly this is covered in the second paragraph of the docs (nuxt.com/docs/api/composables/use-fetch) starting with "useFetch is a composable meant to be called directly..." 👀 But if you think the video helps, feel free to add it to the docs with a PR! 🙏🏻
Thank you for this valuable information. I ended up using $fetch with some handling arround as you told. In my project structure I always keep apis in a seperate layer.
@@TheAlexLichter Since yesterday, I have been trying to understand "nuxt layers" so that I can use it in my project. 😊😊 it is hard to understand for me
Hi Alexander, I just discovered your new channel. Great content!!! I'm pretty sure you will be very helpful with the lack of content for Vue and Nuxt users in YT! I'm currently working on a project where I need to fetch data from an API and I'would like to abstract all the fetch requests made from all the services to a generic file which I will be calling from the services. Will you use $fetch or useFetch in this case? The thing is that there will be cases where the service will be called from a top level and others where it will be called from a function, event handler, etc. How will you handle this? Thanks in advance and congrats for the 3K subs! 😉
Thank you Bernat! I'll keep going 🙌 What I would do: Abstract it using $fetch and then use useAsyncData to call the service/repository 👍 This way you still have the chance to use either
Ok, so I shouldn't be using useFetch in my useAPI composable from what I gather here. Basically, use $fetch inside the component and only useFetch when doing server-side rendering tables? So do I just pass the updated page, sort and other values to the params and it automatically updates?
Using useFetch in another composable is fine. Then it is about how you use that composable eventually (also shouldn’t be initialized in an event handler).
Hey Alex! Thanks for all your content! Please, please! Make a video about the difference between useFetch and useAsyncData if they in theory do the same thing, like refresh on value change. When to use which? Also, another thing. When do I create a plugin and when do I create a composable? What's the differences? Just some suggestions for content that I know others must have too.
Awesome! I ended up calling the execute/refresh function in the onMounted method and it solved the error 'Failed to parse URL from api/x/x' I got when doing a hard update of the page.
Thank you so much. One thing I wanted to know is, because the watch is set to "false" does that mean the execute function calls with the parameters at server render time and not the current values that have been set on the ref in the client side?
Great video! Sometimes I see await being used with useFetch to load some data in script setup. What considerations do I need to make to use await or not if I just want to load the content for the page?
Thank you for the video! Do I get it correctly that in a case of a infinite loading aka "Show More" button which many online shops use to display their products useFetch/useAsyncData is not an option and should use plain $fetch, because upon clicking "Show More Products" previous data (already rendered data) should be merged with a newly fetched one in order to display previous and new one at the same, right ?
Great explanation, I would like to know how to deal with slow API responses. Using useFetch blocks the whole page loading while awaiting the response. What is the best way to deal with that?
That's a bit tricky with SSR, as all data needed for the rendering have to be fetched beforehand. When not using SSR or thinking "only" about client-side navigation, use useLazyFetch/useLazyAsyncData ✔
I was using useFetch wrong. I had the same scenario. Thanks for the video! I just wanted to know about the $fetch wrapper that you mentioned at the end of the video. I've seen in the nuxt docs a custom useFetch which takes a custom $fetch instance but then it's wrapped into a useApi composable which has the useFetch composable. So, if I want to make that fetch wrapper, should i use that custom $fetch or create like a useRawApi that will use that custom fetch instead of the useFetch composable? Hope it makes sense, thank you again
Thanks ! another question about useFetch usage: on a page, I make a simple query (with useFetch) to an internal api server route that fetches some data from an api. till then everything is fine. But why does it keep fetching even with a routeRule of swr:true for that page ? .... isn't it the point of routeRule to avoid fetching and return cache for a period of time ? If I put the routeRule on the server it is better but there is really something I don't get about cache managing. Can you explain this ? Thanks !
routeRules for path only work on the inital request, not when navigating client-side to it :) So yes, using SWR, on both, the api routes and the client make sense.
I have data that is necessary for server side rendering and I'm using GraphQL so it means I need to send a POST request to get that data. Will $fetch do the SSR magic for me?
Hey Alex, what do you think between using useAsyncData() (useFetch() for syntactic sugar of course), and wrapper from tanstack vue-query like useQuery()? Personally, I really loved vue-query approach because it felt so much simpler, and also has a wrapper for mutating data too, while useAsyncData() sometimes felt like there's this complexity that somehow feel enigmatic too grasp even when you read the documentation By the way, great video. Really helpful for me to understand it
Can you do a video about useAsyncData next? My understanding is that I should use useAsyncData if the application should wait until an API has been called. For example:the User navigates to a page that fetches to dos but I don't want to show a loading spinner. Instead, I want the application to wait before it navigates to that page until the API call has been resolved.
Thank you for making such great videos, Alexander 😊. I have a question: Can i use useFetch in Pinia (in SSR Mode) to fetch data and share the returned data between components? By which to get use of transform & getCachedData options. 10:30
Hi Alexander, thank you for this awesome video. The docs says that using $fetch without useFetch/useAsyncData causes fetch data twice, so how can I avoid this behavior using SSR? Should I run the $fetch using process.server and cache this data with useState?
No, you’d just use useAsyncData or useFetch then. But eg the handler function for a form submit will never be executed server side, so you don’t have to bother with that
To me this is a prime example of providing a useful tool to the user (useFetch), but actually learning to use it properly, as well as learning the associated $fetch and such makes the process more complex in the end and can lead to errors. Unfortunately, I've encountered this kind of problem several times with the Vue ecosystem
@@TheAlexLichter Well off the top of my head, the template shorthands (v-bind: and : , v-on and @...). Since not everybody use the same notation it makes the code harder to read and not as consistent (I like that v-bind and v-on are explicit, so I tend to use those, but many people don't). Then you'll get stuff like ":key" which have nothing to do with v-bind and it's all pretty confusing. Also this should be resolved eventually so it might be an unfair point, but the option/composition api is confusing whenever looking for solutions to a problem because you first have to sort out the replies where people use the same API and whether they use script setup etc... Sure, an experience vue dev might not be bothered by it but it's the kinds of small things that makes getting into Vue more frustrating that it should be
Re Shorthands (v-bind: vs. : / v-on vs. @): I think in 99% of all cases you'll see the shorthands and rarely the "full directives" because you use them so often and an "@click" or ":class" should give away the context quickly. There is still good reason for v-bind, e.g. to bind a whole object (e.g. { class: "abc", myProp: "bcd" }) instead of :class="obj.class" :my-prop="obj.myProp". Same for listeners which is more rare though. If you stick to what people + the docs use, which is the shorthands, things should be fine. The only "downside" is you have to remember what is what, but "v-bind:" has the colon already and "listeners -> add -> @" as a little mnemonic. Re OAPI/CAPI. Yes, absolutely. Interestingly, Evan was telling a bit more about that on our recent podcast episode dashboard.transistor.fm/shows/dejavue/episodes/ten-years-of-vue-with-evan-you/ and that it will be easier for newcomers to vue in the future by mainly educating about CAPI.
Does the same apply to any composable, even if it doesn't have async logic? should ALL composable be always on top level or they could be used inside functions?
Yes, this applies to all composables! Important to mention that you can write functions calling composables which are then also composables again (and shouldn’t be called on button click or similar)
after solution 2 settings we can't update body right? i tried but it makes the request with initial values of the body. cant we pass updated data with execute or something? or am i just doing wrong?
Can I use useFetch or useAsyncData (or maybe with Lazy) in the composables function and export the execute/refresh function? I use the trpc-nuxt module and it leverages useAsyncData.
I'm making a module following the author's guide, but I'm having an issue resolving an npm library using the resolvePath() function. Could you please help me??? 😅
I do! You have E2E typesafety if you use /server/api endpoints, so that isn't a problem. More type-safety is work in progress (params & body). Otherwise, you can always use useAsyncData with your favorite validation library like valibot, zod or similar 👌
@@TheAlexLichter Well, I had "individual lessons" (thanks again) on that topic, so I recognized the error... which is a good sign, right? 😁 Still learned something new; how using useFetch wrong can lead to multiple unwanted API calls. I think that now I understand the difference between $fetch and useFetch quite well. So keep up the good work. I'll surely provide more newbie questions in the future! 😂
how about i want to grouping the useFetch in another file, like composables/service/authService.ts how i can call it in my .vue pages without wraping the useFetch with function ?
well, if you have a function calling useFetch it is a composable, see ruclips.net/video/N0QrFKBZuqA/видео.html That's fine as long as you follow the "composable rules" for this function then too :)
Im afraid the principles of composables are necessary to learn! Axios is not a composable but a fetching library such as ofetch, or plain fetch. You can use axios with eg useAsyncData easily but still need to understand it
What a bad example. WHy you you use computed property tu call multiple request.? What's a point? Just get rid of computed to avoid multiple request and that's all.
Even without the computed property, you use a **composable** outside of a vue context, creating possible memory leaks and other side effects you definitely do not want 🥴
No, that's no memory leak. I mean that you create a composable "instance" which can't be cleaned up easily as it'd be the case when defining it top-level.
Not entirely sure what you mean 👀 This video is how to use data fetching composables right. Nobody is talking about "how hard it is to fetch data from the server" 👌
Did you misuse useFetch before? Let me know! 👀
yes, I'm guilty. thanks for the clarification.
Not guilty yet, I'm building a big nuxt 3 spa and mutation of data is just on my list. So this comes in handy.
For now I'm only getting and based on url change, which I made a computed for, or query change, which is relying on pinia state, I refetch the data using useFetch reactivity. In one or two cases I use immediate false and execute useFetch from a watch, which works great as well.
Submitting data is something I will start with just this week, so I will keep this $fetch pattern in mind. In onSubmit I then can collect formData and post it, when form validity is correct of course.
It's luck so far, didn't know composables could lead me into this kind of trouble. Only top level, Tarabass, only top level. Will help with code review as well! Thx
I think I am guilty yeah, I have the following in my pinia store:
const getDeck = async (id: string) => {
const { data } = await useFetch(`/api/decks/:${id}`, {
method: "GET",
headers: useRequestHeaders(["cookie"]),
})
deck.value = data.value
}
Perhaps this should be using $fetch and then wrapping the call to getDeck in an useAsyncData on the component/page ?
@@bennyzenNo worries at all! Time to fix that now 😛
You are welcome ☺
@Tarabass Perfect timing then 🙊
Yeah, using composables not in the vue context (but in "event handlers", watchers etc. etc.) can really cause trouble 🙈
You are welcome 🙌🏻
I cannot emphasize on how good this video was. I personally want to switch from the vue to nuxt, and these videos are clear and helpful. Thanks Alexander !
Much appreciated and very happy to hear this! 🙏🏻
As a fun fact: the same “problem/concept” applies to any data fetching composable, also in plain Vue!
Perfect timing for this video! Thank you so much.
I just stumpled upon a video of yours over on the vue school channel and then saw this video on your channel. I started developing an app using nuxt a few weeks ago and am at the point where it is starting to become more complex. I was really struggling with the API and with useFetch - your video made me realize that I don't need useFetch for what I am doing and that I am better off just using $fetch.
Thanks for sharing that! I’m glad that the content helped you early on 👍🏻☺️
Thank you for these short, straight to the point video's! It's of great help and easy to reference to when needed..
You are welcome 🙏🏻
aww maan, this video couldn't have come in a better time. I'm still processing how lifesaving this was. Thanks!
fyi ... i misused it 🤣
Nice to hear it was helpful and came right in time 🙌🏻💚
Thanks Alex! I'm so new to Nuxt that I haven't even fallen for this trap yet lol (building a thing as I learn 🤓). I appreciate the info, and best wishes!
Haha, even better! So now you won't ever trap into that 👍🏻
Best of success ☺️
love the videos, especially how concise they are. I was curious if you ever considered posting these pieces in text format (either on a blog or a twitter thread)
Thank you 🙏🏻
Actually yes! When I have the time I want to post them on my blog too ☺️
Thanks for the info, It seems like the documentation needs help with this explanation since it's easy to use incorrectly. Maybe adding this video xD
Interestingly this is covered in the second paragraph of the docs (nuxt.com/docs/api/composables/use-fetch) starting with "useFetch is a composable meant to be called directly..." 👀
But if you think the video helps, feel free to add it to the docs with a PR! 🙏🏻
Thank you for this valuable information.
I ended up using $fetch with some handling arround as you told.
In my project structure I always keep apis in a seperate layer.
You are welcome! Glad it helped ❤
This video literally saved my life. This was just in time!!
Glad to hear 🙏🙏
I have been looking for a solution to this problem for 3 days and now I understand that I was using it wrongly.
thank you very much 💕💕
Great timing then 🙏🏻 You are welcome! 🔥
Anything else you are stumped about?
@@TheAlexLichter Since yesterday, I have been trying to understand "nuxt layers" so that I can use it in my project. 😊😊
it is hard to understand for me
@hamedfaryabi1030 maybe my talk on it helps a bit - see ruclips.net/video/ZsPlphW-z5k/видео.html
Damn, i exactly miss used useFetch as you mentioned in the video, you helped me in Discord.
Thanks
You are welcome pal ☺️
Hi Alexander, I just discovered your new channel. Great content!!! I'm pretty sure you will be very helpful with the lack of content for Vue and Nuxt users in YT!
I'm currently working on a project where I need to fetch data from an API and I'would like to abstract all the fetch requests made from all the services to a generic file which I will be calling from the services. Will you use $fetch or useFetch in this case? The thing is that there will be cases where the service will be called from a top level and others where it will be called from a function, event handler, etc. How will you handle this?
Thanks in advance and congrats for the 3K subs! 😉
Thank you Bernat! I'll keep going 🙌
What I would do: Abstract it using $fetch and then use useAsyncData to call the service/repository 👍
This way you still have the chance to use either
@@TheAlexLichter Good point! I'll try it this way. Thanks a lot for answering 😊
Ok, so I shouldn't be using useFetch in my useAPI composable from what I gather here. Basically, use $fetch inside the component and only useFetch when doing server-side rendering tables? So do I just pass the updated page, sort and other values to the params and it automatically updates?
Using useFetch in another composable is fine. Then it is about how you use that composable eventually (also shouldn’t be initialized in an event handler).
Hey Alex! Thanks for all your content! Please, please! Make a video about the difference between useFetch and useAsyncData if they in theory do the same thing, like refresh on value change. When to use which? Also, another thing. When do I create a plugin and when do I create a composable? What's the differences?
Just some suggestions for content that I know others must have too.
Really good suggestions! Added both to the list 🙌
Any code example about useFetch wrapper & $fetch wrapper with ts so we can wrap it and still got the correct result from the useFetch & $fetch types?
Happy to provide one.What exactly should the wrapper do/cover? 🤔 Adding some headers?
@@TheAlexLichter wow thanks! adding some header like Authorization would be really useful
another amazing video about Nuxt, thank you so much men, it was really helpful. keep going.
This made me laugh had this issue using usefetch wrong but now I really understand why! Thank you 😁
Glad it helped! 👏
This content is so informative and did solve my problems !!! Thanks a lot
You are welcome 👌
Honestly, $fetch is just more straightfoward for POST requests. Keep it simple!
Absolutely 🙌🏻
Awesome! I ended up calling the execute/refresh function in the onMounted method and it solved the error 'Failed to parse URL from api/x/x' I got when doing a hard update of the page.
Glad it helped!
Thank you so much. One thing I wanted to know is, because the watch is set to "false" does that mean the execute function calls with the parameters at server render time and not the current values that have been set on the ref in the client side?
Great video! Sometimes I see await being used with useFetch to load some data in script setup. What considerations do I need to make to use await or not if I just want to load the content for the page?
I wish I could easily answer that question 🙈
Might be something for another video 😅
@@TheAlexLichter That would be great!
Thank you for the video!
Do I get it correctly that in a case of a infinite loading aka "Show More" button which many online shops use to display their products useFetch/useAsyncData is not an option and should use plain $fetch, because upon clicking "Show More Products" previous data (already rendered data) should be merged with a newly fetched one in order to display previous and new one at the same, right ?
I can watch very useful videos until the morning
I hope more content will come soon so you actually could 😜
In the meantime, the livestream recordings also have a gem or another 👍🏻
Great explanation, I would like to know how to deal with slow API responses. Using useFetch blocks the whole page loading while awaiting the response. What is the best way to deal with that?
That's a bit tricky with SSR, as all data needed for the rendering have to be fetched beforehand.
When not using SSR or thinking "only" about client-side navigation, use useLazyFetch/useLazyAsyncData ✔
thanks man. your video should be top 1 nuxt 3 official documentation
Thanks 🙏🏻
Still want to link them in the docs for more context.
this was an amazing explanation, thank you Alexander!
Happy it helped 🙌
This is so useful, thanks for making the video!
Glad it was helpful! 🙏
I was using useFetch wrong. I had the same scenario. Thanks for the video! I just wanted to know about the $fetch wrapper that you mentioned at the end of the video. I've seen in the nuxt docs a custom useFetch which takes a custom $fetch instance but then it's wrapped into a useApi composable which has the useFetch composable. So, if I want to make that fetch wrapper, should i use that custom $fetch or create like a useRawApi that will use that custom fetch instead of the useFetch composable? Hope it makes sense, thank you again
Happy to hear I could help!
wrt to custom $fetch, check out ruclips.net/video/jXH8Tr-exhI/видео.html
Thanks ! another question about useFetch usage: on a page, I make a simple query (with useFetch) to an internal api server route that fetches some data from an api. till then everything is fine. But why does it keep fetching even with a routeRule of swr:true for that page ? .... isn't it the point of routeRule to avoid fetching and return cache for a period of time ? If I put the routeRule on the server it is better but there is really something I don't get about cache managing. Can you explain this ? Thanks !
routeRules for path only work on the inital request, not when navigating client-side to it :)
So yes, using SWR, on both, the api routes and the client make sense.
Great video Alexander! But I am curious, what if we use a non-ref value for the body?
While you wouldn’t see a huge amount of requests, you’d still introduce a memory leak because every function call will create a new composable
Ah that makes sense. Thanks a ton!@@TheAlexLichter
would love some intro to testing nuxt 3 videos! keep em coming
Is one the list, now that nuxt test utils contain both, vitest + e2e integration!
Nice! Excited for that. Think the community will be very happy!
I have data that is necessary for server side rendering and I'm using GraphQL so it means I need to send a POST request to get that data. Will $fetch do the SSR magic for me?
Good question! Not it won’t. For GQL, use useFetch for queries 👍🏻
Hey Alex, what do you think between using useAsyncData() (useFetch() for syntactic sugar of course), and wrapper from tanstack vue-query like useQuery()? Personally, I really loved vue-query approach because it felt so much simpler, and also has a wrapper for mutating data too, while useAsyncData() sometimes felt like there's this complexity that somehow feel enigmatic too grasp even when you read the documentation
By the way, great video. Really helpful for me to understand it
Can you do a video about useAsyncData next? My understanding is that I should use useAsyncData if the application should wait until an API has been called. For example:the User navigates to a page that fetches to dos but I don't want to show a loading spinner. Instead, I want the application to wait before it navigates to that page until the API call has been resolved.
The concepts here apply to useAsyncData as well, as useFetch is basically useAsyncData + $fetch 😊
In your example, useAsyncData or useFetch is indeed the way to go if you want to “block navigation”
nice content! thank you and keep them coming ❤
Thanks a lot 🙏🏻
Will do, I promise! 👌🏻🔥
Thank you for making such great videos, Alexander 😊. I have a question: Can i use useFetch in Pinia (in SSR Mode) to fetch data and share the returned data between components? By which to get use of transform & getCachedData options. 10:30
You *could* but it might lead to double-payloads. I suggest using $fetch + callOnce
Thanks 😊
Hi Alexander, thank you for this awesome video.
The docs says that using $fetch without useFetch/useAsyncData causes fetch data twice, so how can I avoid this behavior using SSR? Should I run the $fetch using process.server and cache this data with useState?
No, you’d just use useAsyncData or useFetch then.
But eg the handler function for a form submit will never be executed server side, so you don’t have to bother with that
Amazing, very clear, thank you Alexander!
You're very welcome! ☺️
To me this is a prime example of providing a useful tool to the user (useFetch), but actually learning to use it properly, as well as learning the associated $fetch and such makes the process more complex in the end and can lead to errors. Unfortunately, I've encountered this kind of problem several times with the Vue ecosystem
Which other scenarios come to your mind there in the Vue ecosystem?
@@TheAlexLichter Well off the top of my head, the template shorthands (v-bind: and : , v-on and @...). Since not everybody use the same notation it makes the code harder to read and not as consistent (I like that v-bind and v-on are explicit, so I tend to use those, but many people don't). Then you'll get stuff like ":key" which have nothing to do with v-bind and it's all pretty confusing.
Also this should be resolved eventually so it might be an unfair point, but the option/composition api is confusing whenever looking for solutions to a problem because you first have to sort out the replies where people use the same API and whether they use script setup etc...
Sure, an experience vue dev might not be bothered by it but it's the kinds of small things that makes getting into Vue more frustrating that it should be
Re Shorthands (v-bind: vs. : / v-on vs. @): I think in 99% of all cases you'll see the shorthands and rarely the "full directives" because you use them so often and an "@click" or ":class" should give away the context quickly. There is still good reason for v-bind, e.g. to bind a whole object (e.g. { class: "abc", myProp: "bcd" }) instead of :class="obj.class" :my-prop="obj.myProp". Same for listeners which is more rare though.
If you stick to what people + the docs use, which is the shorthands, things should be fine. The only "downside" is you have to remember what is what, but "v-bind:" has the colon already and "listeners -> add -> @" as a little mnemonic.
Re OAPI/CAPI. Yes, absolutely. Interestingly, Evan was telling a bit more about that on our recent podcast episode dashboard.transistor.fm/shows/dejavue/episodes/ten-years-of-vue-with-evan-you/ and that it will be easier for newcomers to vue in the future by mainly educating about CAPI.
Does the same apply to any composable, even if it doesn't have async logic? should ALL composable be always on top level or they could be used inside functions?
Yes, this applies to all composables! Important to mention that you can write functions calling composables which are then also composables again (and shouldn’t be called on button click or similar)
@@TheAlexLichter Got it! Thanks, Alex ♥
after solution 2 settings we can't update body right? i tried but it makes the request with initial values of the body. cant we pass updated data with execute or something? or am i just doing wrong?
my usefetch is in seperate file and i pass body while calling the function in first place
You can if you pass a computed!
@@TheAlexLichter thanks for your good video. it was about passing computedBody.value to my function. it worked after just passed computedBody
@berkaykarademir8641 on that note check out ruclips.net/video/sccsXulqMX8/видео.htmlsi=9IpRNrLW8hmh3UJn
@@TheAlexLichter thank you. that will help me solve those kinds of problems fundamentally
Then how would I go about fetch data on pageload/ssr, and then refetching the data on a user action?
Use the refresh option of useFetch/useAsyncData or update refs that are watched ☺️
This is awesome man. Thanks!
You are welcome! 👌😊
I cant recreate this, my useFetch does not call on keydown only on button submit.
Probably because you don’t use a computed for eg the body
Still causes a mem leak client-side
Can I use useFetch or useAsyncData (or maybe with Lazy) in the composables function and export the execute/refresh function? I use the trpc-nuxt module and it leverages useAsyncData.
yes, you can do that! 👌
Will work similarly to my 2nd approach shown. But make sure to call it top-level.
Does this behavior only apply to useFetch, or is it the behavior of all composables if we don't use them at the top level of the script setup?
You should not use composables in these handler functions in general :)
Good video, I understand better now how this composable works XD
Glad it helped! 🙌
Thank you! How can i use the second approach with refresh if i have many useFetch?
If you want to refresh *all*, use `refreshNuxtData` :)
Great! thank you@@TheAlexLichter
As usual, excellent video!
Thanks again Josh! Glad you like them 🙏🏻
Hi!
I wonder are there anyway to put value at the time call execute?
Can you help me?
Good morning! How do you meant that? I’m not sure I understand 😊
I'm using useFetch. Any idea why the data is being rendered twice?
Hard to tell without a reproduction I'm afraid.
Hydration errors maybe? ruclips.net/video/TYyEjN0UrfA/видео.html
I'm making a module following the author's guide, but I'm having an issue resolving an npm library using the resolvePath() function. Could you please help me??? 😅
Sure, Message me on Discord 👌🏻
@@TheAlexLichter ohk, thanks. I sent a personal DM if that's ok with you 😅
Wonderful video. Thank you, I learn a lot
Glad to hear that! 🙌
Very useful! Help a lot! Thanks man~
You are welcome! 👌
Is it same applicable for pinia when we call another store function inside store? If yes then how can we resolve it?🤔
A function from a store is not a composable. But useXYZStore is :)
@@TheAlexLichter yes to get that function we need to call useXYZStore() inside some other store. Is that the same issue?
If you call it top level it is fine (composables can be called in other composables) 👌🏻
@@TheAlexLichter how about this ⬇. "useUserStore".
(This "signOutUser" function is in useAuthStore)
async function signOutUser(): Promise {
try {
await signOut();
const { resetUserState } = useUserStore();
resetUserState();
setIsAuthenticated(false);
return {
status: 200,
message: 'Successfully sign out',
};
}....
Nah, I would definitely register the store and destructure outside of that fn and “top-level”
Do you like useFetch? I think it’s missing important things like input types and input & output validation
How do you overcome this?
I do!
You have E2E typesafety if you use /server/api endpoints, so that isn't a problem. More type-safety is work in progress (params & body).
Otherwise, you can always use useAsyncData with your favorite validation library like valibot, zod or similar 👌
I can relate already! 😂🤦♂️
Haha 😂 Let's see what you say after the clip 😜
@@TheAlexLichter Well, I had "individual lessons" (thanks again) on that topic, so I recognized the error... which is a good sign, right? 😁 Still learned something new; how using useFetch wrong can lead to multiple unwanted API calls. I think that now I understand the difference between $fetch and useFetch quite well. So keep up the good work. I'll surely provide more newbie questions in the future! 😂
You are welcome!
That is a good sign indeed ☺️
Thanks a lot - glad it helped! Definitely keep the questions coming 👍🏻
If you are using .value in computed that you wrote in body its work fine and than requests not spends many times
Was already mentioned here but that will *still* create a mem-leak client-side because the composable can't be cleaned up!
btw which browser do you use?
Firefox Dev Edition 👌🏻
Great content, thank you!
You are welcome 🤗
How about use useAsyncData?
The same applies there too! Actually for every composable 👀
As usual, GREAT video
Thanks again! 🔥
Awesome. Thank you
You're welcome!
Great explanation, thanks
Glad you enjoyed it! 🙏🏻
Thanks! that's really helpfull
Yey! That’s how it should be 🙌🏻
Im just using "watch: false" with my useFetch composable in async function.
That will still create a memory leak 🙈
See my 2nd solution for an alternative!
Thanks Alex!
Of course 🙌🏻
Thank you from Ukraine! What about useAsyncData?
Same idea!
Great great content and well explained thanks
Glad it was helpful!
how about i want to grouping the useFetch in another file, like composables/service/authService.ts
how i can call it in my .vue pages without wraping the useFetch with function ?
well, if you have a function calling useFetch it is a composable, see ruclips.net/video/N0QrFKBZuqA/видео.html
That's fine as long as you follow the "composable rules" for this function then too :)
I saw video, and want to ask, what about nuxt-api-party, im now using him and now want to know is he good to use?
Yes, definitely a nice module if you have the need for it 👌🏻
@@TheAlexLichter Thanks!
Yes I learnt this in the hard way. 😂
But you learnt it 😛
I don't use useFetch, I just use fetch
Then you might have issues when doing SSR, as data will be fetched twice!
Nice tutorial!
Thank youu! 🙏🏻
❤
🙌🏻
can i just trash the whole useFetch Bullshit and use axios instead?
Im afraid the principles of composables are necessary to learn!
Axios is not a composable but a fetching library such as ofetch, or plain fetch.
You can use axios with eg useAsyncData easily but still need to understand it
Nice video
Thanks 🙏🏻
fixing fixing 🤫
That’s how it is going sometimes when learning 😁
What a bad example. WHy you you use computed property tu call multiple request.? What's a point? Just get rid of computed to avoid multiple request and that's all.
Even without the computed property, you use a **composable** outside of a vue context, creating possible memory leaks and other side effects you definitely do not want 🥴
@@TheAlexLichter By memory leak you mean sending request every time when you typing something in your form?
No, that's no memory leak. I mean that you create a composable "instance" which can't be cleaned up easily as it'd be the case when defining it top-level.
@@TheAlexLichter Aaa, now i've got it, thanks for the answer and example.
ant title like "You are using xx WRONG!", get mi instant thumb-down
Under condition:
ONLY if you actually never did this mistake 😛
Thank you, it finally clicked!
Yey! Happy to hear 👏🏻
loved
Thank you 🙏🙏
lol fetching data from server is not thay hard. you make things harder just to have a rest api
Not entirely sure what you mean 👀
This video is how to use data fetching composables right. Nobody is talking about "how hard it is to fetch data from the server" 👌
Now i understand correctly. Thank you @TheAlexLichter
You are welcome! 😊