Data Fetching With Nuxt 3

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
when building out applications one of the most common things that you need to do is fetch data and when working with nux 3 it comes with two composes and a built-in library to handle data fetching seamlessly however chances are if you're watching this video you might be a bit confused as I was on which one of these methods you should use to properly fetch data inside of your nux 3 application so in this video we're going to explore these two composes and learn how to use them correctly okay so as mentioned Nu comes with the of fetch Library built in and this gets Auto imported as the fetch utility or dollar sign fetch to use globally throughout your application to make Network requests Nu also provides us with two composes use Fetch and use a sync data that use the fetch utility under the hood to address some of the challenges faced with data fetching since Nu can be rendered on the server and also the client if you were to just use the fetch utility within a nox component to make your network request what ends up happening is the data will fetch twice on the initial load since the fetch utility does not transfer state from the server to the client now the biggest question that I think arises is which one of these methods should you use and that is going to determine based on the type of request you're making or the current situation that you have within your application so the fetch utility is going to be useful for posting data when performing requests that you only need on the client side or you can use it within the use async data composable which will'll be covering more about this in just a few moments now the use Fetch and use async data composable are going to be for your get request or fetching data use fetch is considered the most straightforward way to perform data fetching in a n application this composable accepts a URL as a parameter then it returns data which can then be structured to use inside of your template or your script and most of the time you're probably going to be opting to use this composable to fetch your data now the use fetch composable is actually nearly equivalent to the use a sync data composable it's ESS essentially just some syntactic sugar for the most common use case now the use async data composable is designed for more complex asynchronous calls such as working with third party libraries or perhaps if a component needs to make multile fetch requests while still allowing you to keep the same benefits provided by the composable so how this composable works is for the first pram you provide a unique key that actually gets used to cach the second argument which is going to be the querying function so for example if you wanted to make multiple fetch requests you canate create a promise.all within the function and then we can use the fetch utility to make the request itself and a way for all these to finish and then return the results or if you're using a thirdparty library for example like subase you can use their queries and then just return that data all right so now that we know about all the various methods and composes to go ahead and make Network requests let's go ahead and do a few here inside of a n application so here inside of this n application I have a page called products and if we head over to our browser you can see I have this application spun up and running on Local Host and we have two pages the homepage which we currently on right now and then we also have our products page now what we're going to do is make an API request to this fake store API so we'll want to select on the get all products endpoint and we can just select this URL and then back inside of our next application inside of the script we just want to make this API request and to do this we're going to be using the use Fetch composable and the reason why we'll be using use Fetch and not use a sync data is because this is a very simple API request that we're going to be making and it doesn't require use a sync data however we could use the use a sync data compuls in this example but in my opinion it's a little bit cleaner to use use fetch when you can so what we'll do is we'll create a new variable and we're going to destructure this and we're just going to say data and then we want to reassign this so we don't call it data so it's a little bit more specific so we'll call this products and then we'll set this equal to the use Fetch composable and then we just want to pass in that URL that we copied from the fake store API and what we also want to do is add the keyword of await here and what this is going to do is await for this API endpoint to resolve before loading in this page so if we save this and then what I have already is some preconfigured markup for uh a couple cards to display each product in so we're just going to use a V4 Loop and say for each product that we have inside of this products right here we want to display this card that's going to be in a grid and if we save this and head over to our browser and we head to the products you're going to see that we now have these product cards being displayed from the data that we fetch from our API using the use fetch composable now circling back to this request that we have within our script when we use the await keyword on this use fetch composable what happens is it actually blocks the navigation to this page until this API has resolved and it does this by using one of vue's newer features within vue3 called suspense so right now you're not going to be able to see this if we head back over to our application and we go back to home and we go to products we don't see really any loaded indicator there is a slight delay when we click on products that it takes to actually load in this page it's very minimal but there is a slight DeLay So if we wanted to visually have a loading you know animation or something that informs user that we're working on something we can actually go back to our application and N provides us a built-in component called Nu loading indicator and if we save this and since we have this keyword of a wait here it's going to make this suspenseful and wait for this to finish uh before navigating to this page and if we go back to our browser or the application and we now select on products you can see that we have this nice loading animation that's going to you know inform the user that something's happening while that data is waiting to resolve now if if you do want to bypass this default Behavior what you can do is the use fetch compol will actually does accept a object for some additional options and we can pass the lazy property and set this to false and then we just want to remove this awake keyword however if you do do this then you need to handle a loading State yourself inside of this component so we can actually destructure a second value from this composable and this is called pending so what we can do is we can create another div and and we'll use a v if directive and we'll say if pending is true then we'll just have a paragraph tag within here and this will say loading otherwise we'll display our grid with all of our cards and now if we navigate to our products page as you can see there for a brief moment we're going to have our loading text and then once our API has resolved then we're going to see our product cards and alternatively what you can also do is instead of having to pass this object with this property of lazy set to false we can remove this and there's actually a second composable for use fetch which is called use lazy fetch which does the same exact thing now if you recall the reason why this composable was created was to alleviate the challenges that we had while using Nu since it's universally rendered that means that the initial page load happens on the server side and once the page is loaded in all the other navigation done happens on the client side now in some cases you may not want to fetch that data on the server site and you only want it to happen on the client site and you can do that very easily still using this composable by passing a second or another property inside of our options object called server and we can set this to false and with the set def false this API endpoint is no longer going to be executed on the server side and it's only going to be executed on the client side and if you pair it up with the lazy property set to false or you use the use lazy fetch this can be a good way to handle data that is not needed on the first render for example anything that is not important to your SEO now for this API request that we're making we're getting back an array and we're referring to that array as products and We're looping over that array and we're outputting a card for each product that we have in that array and then we're outputting the image and the title within that object now if we head back over to the browser and we open up the Nu Dev tools which if you haven't heard of the Nu Dev tools I do have a first look video and I'll leave that link down below the description we can actually gain access to the payload on the specific page which you can see right here it's going to be Auto keyed for us and if we open this up we can see that we have the whole entire payload that we're getting back from our API so if we open this up you can see we have the ID the title price and we have a couple different properties in here now like I mentioned we're only really using the title and then the image we could probably also use the ID to provide a unique key for each one of our uh cards but you can see we're only using maybe three of these properties so if we wanted to we can actually limit the properties that get returned while using the use Fetch composable and to do this inside of our options object we just want to pass a new property called transform which accepts a callback function so as a parameter we're going to pass in our products that were being returned here from our use Fetch composable and then within here we're just going to return and we're going to map over the products that we have and we're going to create a new object with only the properties that we want which is going to be our ID our title and then our image so if we save this and we head back over to the application and we look at our data or our payload here inside of the no Dev tools you can see that we only have the three that we specified which is the ID the title and the image now in this API request the return value was an array and to properly go ahead and pick the properties that we wanted returned in our payload we have to use a transform property along with the map method now if we were using a API request that returned maybe an object which you know happens if you're getting a single product for example we can actually use a different property within our options called pick and this is an array and we can pass in the properties that we want to be uh inside of our return payload so again we can say the ID we can say the image and then also our title so now if we save this and we head back over to our application you can see their application is going to look a little bit weird but if we do a refresh and we can open up our payload and as you can see we have those three properties that we requested so if the API request that you're making returns an object you can use the pick property like this otherwise if you're using an array you want to use a transform property and it is worth noting that this transform property does not prevent The Unwanted data from being fetched initially however it will prevent The Unwanted data from being added to the payload that is transferred from the server to the client all right so there may be a case where you want to refresh this data from our API without having to refresh the entire page or application and we can do that quite easily using this composable so we're already D structuring this pending and also our data which we're reassigning to the value of products we can uh destructure a function from this composable called refresh and then what we can do is inside of our template we can come up here with within this we can just create another div to wrap everything and then we can move this vlse directive to this div here and then we can just pull all this stuff inside of here and then we can create a button and then what we want to do is every time we uh we click on this button so we'll add a click Handler we're going to run our refresh function and we'll just say refresh data like this and now if we head back over to the application you can see we have this button and if we click on it it's going to then refetch all that data for us okay so we took a look at some of the more common use cases you may need to utilize while fetching data using the use fetch composable so what I want to show you now is an example of fetching data using the use a sync data composable so maybe instead of just wanting to make one request to our API we want to make two request to a separate endpoint so if we head back over to the fake store documentation so right now we're getting all the products so maybe instead of just doing that we also want to get all the categories and combining these two would make a good use case for using the use async data composable okay so let's start off by commenting out our previous request that's using the use Fetch composable and then what we want to do is we'll create a new variable and we'll do some destructuring very similar to what we have here with our use fetch composable so for now we're just going to extract the data and instead of calling this product our product we'll call this product info and then we'll set this equal to the use async uh data composable now the first param here that this accepts is going to be our key so what we'll call this key is product info and then the second pram is going to be our querying function and we'll also want to make this call back asynchronous so we'll just put the keyword of a Sync here now if we wanted to have that page blocking navigation where we want to wait for our API to resolve before we load into the page we could use the keyword of await and that's going to block us loaded into the page until we have this resolved or if you want to use the same method we currently have within our use fetch we can pass a third pram with our options object and we can pass in the lazy property and set this to false and if you don't want to pass this third pram for your additional options with this lazy property what you can do instead is I have a alternative composable for this called use lazy async and this will do the same thing as setting this lazy property to false but we're just going to use the property lazy so I'm going to remove this okay so then inside of our quering function we just want to make our request to our API so what we're going to do is we're going to use a promise.all for this so we'll say cons for a new variable and then we're going to destructure the response we get from this so the first one we'll just call products and then the second one will be categories and then we'll set this equal to a new promise.all and then within here we're going to have our array and I spelled this wrong so it's spell categories right so inside of this promise.all array what we want to use is that Global import of fetch so we'll say dollar sign Fetch and then we're going to pass in the URL that we want to make our API call to so the first one's going to be our product so we'll just copy this and then the second one's going to be be that category's uh endpoint so let's head back over and we'll recopy this and then what we'll do is we'll say dollar sign fetch once more and then we'll paste in that endpoint like this and then what we want to do is after this we just want to then return the inside of an object the products and then the categories and since we're using this lazy property we're also going to need to destructure the pending value from this and then as you remember we also have the refresh so we'll also destructure that as well and then what we want to do inside of the template here because now if we take a look at our application currently it's not going to show any data so if we head over to the NX Dev tools and we look at the payload you can see we now have this product info which was the the key we gave it within our composable you can see that it's actually null so let's do a refresh of this and if we open this up now it is still null so the reason why it's coming back null is because we're actually not awaiting for this promise at all to finish so if we add that await keyword we save that and then we refresh our data or just refresh the page for some reason that doesn't seem to work and now we take a look we should now have our products and then our categories so what we want to do is currently right now We're looping through the products array which doesn't exist so it actually now exists on this product info so instead of just saying products we're going to say product info. products and if we save that we can now see we have all of our information again being displayed in the application but this time instead of using the use fetch composable we're using use async data and we're also making a additional API request so what I also want to show you is how we can still use a transform property while using the US use a sync data composable to manipulate the data that we're receiving back within our payload so to save some time what I'm going to do is inside of our options object I'm going to paste in the new transform property so it's going to look very similar we're still going to have our callback function but this time instead of passing just product we're going to pass in our product info which is a data that we're just structuring back from this call and then within this callback function we're going to return a new object and since we're also obtaining the category and we don't want to manipulate these we're just going to return them as they are and then for the products we're going to do our matap method again and we're just going to create our new object which is the same way that we did it here within our use Fetch composable and the only difference that we have is instead of just referencing our products we first want to reference the product info pram all right so if we save this and head back over to the application and we do a refresh and we take a look at the uh payload and then we look at the product as you can see now instead of having all those values being returned for each object we only have the three that we specified now when fetching data one common thing that can happen is errors and you want to be able to account for those and these two composes make it very easy to do so so what we can do is there's actually a additional value that we can destructure from these composes called error and then we can display this eror inside of our template so let's go beneath our loading indicator and let's create a another div and we're going to say V else if and we only want to show this if we have an error and then what we can do is output the following error properties so let's create a few paragraph tags and then we'll just say the error code like this and then we can say error. status code and we can also output the error message so we'll say error message like this and we'll say air. message and if we save this and head back over to the application and we look at our product products page well we're not actually going to have an error so we can maybe manipulate this and what we can do is we can just remove this like that and now if we save that and as you can see we have our erir code being displayed and also the air message so anyways that's going to wrap it up for this video hopefully you found it helpful and you now have a better understanding of how to perform data fetching within your next application so just to summarize the use fetch composable is going to be the most straightforward way to make API requests Within your application and most of the time you're probably going to be opting to use this unless you need to perform some sort of complex asynchronous logic in that case you're going to use the use a sync data composable and what I mean by that is if you wanted to make in a away multiple fetch requests as we did here inside of this example or perhaps if you're working with a third party library now although we covered a lot of the common use cases when it comes to fetching data within your next application we didn't quite cover everything so if you are interested in learning a little bit more about things I definitely recommend checking out this data fetching section that they have within the N documentation and I'll leave a link to this down below in the description as it has a lot of good knowledge when it comes to data fetching within your nux 3 application so anyways if you did enjoy the video and you want to see more Nu content like this on the channel be sure to like And subscribe and if you are interested in learning more about Nu I am working on a course that is not quite out yet but if you do want to join the wait list you can head over to learn N.D but thank you for watching I'll see you in the next one take care
Info
Channel: John Komarnicki
Views: 14,829
Rating: undefined out of 5
Keywords: vue, vue 3, vue js, john komarnicki coding, nuxt, nuxt 3, data fetching, nuxt 3 data fetching, data fetching nuxt 3
Id: yk80g6QS30Y
Channel Id: undefined
Length: 20min 31sec (1231 seconds)
Published: Fri Oct 27 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.