This episode is for members only

Sign up to access "Getting Started with Nuxt 3" right now.

Get started
Already a member? Sign in to continue
Playing
12. Fetching within components

Transcript

00:00
As well as using useFetch in our pages, we can also use these in our components. Let's take a look at an example. Now in the navigation, we might wanna make a request
00:10
to list how many to-dos we have overall. This isn't the greatest way to set this up, but it's gonna give you an example of how you use this component level.
00:21
So normally we would use state management for this, but let's go ahead and use our script to just make a request to the same endpoint and then use JavaScript's length property
00:32
to grab back how many to-dos we have. So inside of here, we can do exactly the same thing. Let's go ahead and define this out and we'll await useUseFetch,
00:42
which we can use in our components. And let's go ahead and grab the URL for this. We'll make a request to this and then we'll go ahead and extract that data out
00:52
and just call that to-dos in here. So now that is technically making another request, but within this nav component. The same thing applies.
01:02
We can defer this if we want to. So you could use defer true if you needed to. Probably a good idea at component level if you were doing this.
01:10
So now what we can do is on to-dos, simply output the count. So we can say to-dos length, and let's check it out.
01:19
Give that a refresh and there we go. We have 200 to-dos on here and that's always visible at that component level. Like I said, if you wanted to,
01:27
you could go ahead and add a defer on that. Let's do that now. And let's come over and check out the difference. You can see that it doesn't look too much different.
01:34
We just have a period of time where this isn't quite available. That's absolutely fine. So that is pretty much how we would use this
01:42
at a component level. We can use useFetch for this really nicely within any of our components and make a request in exactly the same way.
18 episodes1 hr 15 mins

Overview

Nuxt is a framework built on Vue that makes development of applications a breeze. In this series, we'll get set up with a fresh project and work through everything you need to know to start building with Nuxt.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Episode discussion

No comments, yet. Be the first!