Data fetching in NextJs using SWR

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
let's talk about client side data fetching in xds applications now you might think why would i want to fetch data on the client side since i have access to static site generation server side running in next gis why would i fetch to the client side now if your page doesn't require seo or that the page or the data is so dynamic in nature that makes sense to fetch it on the client side you can use this as strategy think of a shopping cart page that's very dynamic in nature you can fetch the changes or updates on the client side or think of a profile page which doesn't require seo because you need to be logged in so it's not even seen by search engines you can use client-side data fetching now to demonstrate this we're going to start the standard reactive we're going to use user state use effect and the native feature api and fit some products to show on our page then we're going to do the same thing with a third-party package called swr which makes client-side data fetching easier and it comes in with built-in features such as revalidation and then at the end i'm going to also show you how you can combine static site generation with client-side data fetching and the idea being that you would build your site statically but then update any changes on the client side so let's jump in for this i've created a brand new create next app and i've changed the content of the home page the index.js page to this simple little component that shows this home page as you can see on the right-hand side i've also went ahead and created a real-time firebase database to hold some products that we could fetch and show on our pages they have names images and prices so let's actually do that in our pages folder i'm going to create a folder called products to hold my products page i'm going to create an index.js x here that holds our page component and i'm just going to say product page let's actually test that this is working so we're going to go to products page and there you have it we have the products page let me just open the console here so when we need to see things in the console we have it right there so let's bring in user state and use effect from react and introduce some states and send a fetch request to get our products i'm going to introduce or start from my product state and i'm going to initialize this to an empty array then i'm going to also introduce a loading state for when we're sending the request i'm going to initialize this to false and i'm going to also introduce an error state and i'm going to initialize this to null okay let's continue with use effect this is going to be where we actually send the request so i'm going to create a function called fetch products it's going to be an async function and we're going to define our endpoint as the url let's just bring in our url from firebase so let's just copy this link and bring it here the way that you have to call your data or endpoints in database is that i'm going to get this json data as i can see here from this endpoint i'm going to add the name of this key which is the products.json to get the data there so let's actually do that so i'm going to evade sending a fetch request to that endpoint sorry url and then i'm going to resolve the response as json let's actually console.log the data and see what we get back we need to call this function fetch products okay let's go back and then look at the console let me just refresh and we are having that same json object back with p1 to p4 keys each pointing at a product object so we have to transform this into an array so that we can set our product state so let's actually do that for this i'm going to create a an empty array called loaded products let's call it and for each key in the data object sorry khan's key in data i'm going to get the loaded products and i'm going to push an object which is the data at that key okay now let's actually log this load of products and see if everything is working correctly just refresh you also just make this a bit bigger so yeah we have an array of products objects uh each have a name image and a price an id that we could use to show on our page now that we have transformed our json data into an array let's actually go ahead and set our state for products to that transformed array now that we have this array let's just go ahead and show it down here so for every product in our product state or in our product array i'm going to map the product to a product component that i have created before so let's just see what this component is this product components it's going to take a products prop it's going to destruct your name image and price from it it's going to render a list item well obviously because it is inside of an unordered list down here and it's going to show an image the name and the price so pretty simple as you can see we have our products fetched and shown on the right hand side now you might think we are still not using these two states the loading and error state so let's actually go ahead and use them before i send this request here i'm going to set the loading state to true and i'm going to also clear out any previously thrown errors if you're successful we're going to set the products and if you're not you want to catch the air so i'm going to call catch i'm going to pass the error here and then finally what we want to do is we want to set the loading back to false now that we have taken care of this reset let's actually go ahead and use them so if there is an error i'm going to return a div that says failed to load and similarly if i'm loading or if we don't have any products i'm going to return a div that says loading okay now just to show or reiterate that this is fetching data on the client side if you view the page source and make this a bit bigger you can see uh our page is actually empty it's just a div of loading this div over here because we don't have any products in the beginning until the javascript loads and then actually sends a fetch request and then gets the data back re-renders the page and we can see everything over here just to show that it is client-side data fetching okay great now let's do the same thing using swr so swr is a library of react hooks for data fetching on a client side the name is derived from an http invalidation strategy called stale while revalidate in the sense that swr package first returns the data from the cache hence the name stale and then sends the fetch request to revalidate and then comes back up with updated data this way our components have a stream of data which updates automatically so it's faster as i mentioned earlier it comes in with some built-in features you can review on the documentation page one of the most interesting ones is revalidation on focus or revalidation on intervals we're going to see this in action at the end once i build the project now to use this we have to go ahead and actually install the package so i'm going to stop the development server i'm going to run npm i uh for install swr okay great let me just restart the development server now to use this i'm going to create a new page in the products folder and i'm going to call this swr jsx now let me just initialize our page component or function that's going to be swr now to use this we need to import this usswr hook like so and then we'd have to call this hook from inside of our page component we're going to have to need to pass it an endpoint and a custom fetcher function in return it it gives us back the data and it manages the error state or the loading state as it is sending this fetch request so let's start with defining this custom fetcher function for it i'm just going to use the native fetch api so i'm going to get the arguments and i'm going to call the fetch i'm going to pass in the arguments and i'm going to then get the response and resolve it as a json let's actually bring in the url or our endpoint from the previous page so i'm going to bring that in over here and i'm going to pass this url to this hook and get the data back just close this okay now here i'm going to say if there's any error similar to the previous step we're going to re return a div that says fail to load and if there's no data well perhaps vr lodec now once we have our data back we have to go ahead and transform it remember that firebase sends the data back as a json we need to transform it into an array and once we have an array we are actually going to just render the same thing we did over here so i'm just copy pasting the code we've already had there we're going to copy copy paste this and instead of the products i'm just going to pass in order map over the loaded products let's just also bring in the products component so this guy and this should be working so we're going to go to products for slash swr this is just the page we created using the swr package as you see we see the same result over here but the benefit is that we just had to write this one line of hook pass it the url and then it gives us the data back it manages the error and the loading state in the sense for us without us having to manage through different states or using use effect to actually send the request so it's easier and it also as i mentioned comes in with built-in features it's faster it returns data from stale first then revalidates it also revalidates on intervals and on focus which we're going to see at the end now let's actually go ahead and combine static side generation from next js with client-side data fetching again the idea is that we want to build our site statically but then if there's any changes in our data between the time that we have deployed our app and the time that the user visits our page we want to fetch that update on the client side so let's go ahead and create a page called ssg standing for static site generation with swr jsx again similarly we're going to initialize our page component now if you want to instruct next js to generate a page statically you have to export an async function called get static prop from your page inside of it we're going to fetch the same data that we've been fetching client side but this time on the server side so i'm going to bring these two lines from here and we're going to hit this endpoint with fetch and then get the data back and what we're doing here we're going to return an object with the props key from this function that has a fallback set to an object that maps this specific endpoint to the data that was returned from it now that we have access to this fallback data we can share it to our uswr hooks on the client side for this we're going to use a component from swr called swr config this is a context provider used to share configuration options between all of our hooks but one of the things we can also share is a fallback object that maps endpoints like urls to the data that's returned from them so our hooks the uswr hooks can use this fallback data as the stale data they return first before they revalidate so let's let's actually go ahead and bring this swr config in our page and then we're going to put a value here which is an object with this fallback data now for this inside i'm going to actually render a product list that i've created before i'm going to show it to you in a second now let's look at the product list this component is a similar component to what we have created before and uses the uswr hook just as we use it before and fetches the data to that same endpoint and then transforms the data and shows the data the same way they've been doing it all along but this time because we are rendering this product list inside of this swr config which shares this fallback data mapping urls to this or endpoints to this data it is returned from it from the server side this hook now has access to this data to begin with so this data is never null to begin with and as you can see i don't i'm not destructing the error here either because the data is already there so our hook has this tail data that was fetched from the server side to begin with and then it can revalidate on the client side so let's actually save this go back here save this and this should work so let's go to our page go ssg with ssg with swr and we can see our products once again there but the interesting thing this time is if i view the page source you can see our page isn't empty anymore it has data built in so the initial html came in from the server has data but then uswr is going to kick in on the client side and revalidate this data that was provided as a fallback to it from the server side let's actually see this in action i'm going to build this project so let me stop the development server i'm going to run npm run build to build a production bundle then we're going to use npm star to actually spin up a server that runs that production bundle so just go ahead and do npm start this time and now if i go to products this is now the production bundle let me just view the page source this for slash products is when we are fetching data using standard react way use the state and use effect you can see if you're rendering a div with loading no data in here and if i go ahead and go to force swr same thing using the swr package but then when i view the page source again i don't see any data it just says loading i close this off and then i go ahead and go to ssg with this wr i see the same products but this time when i view the page source my page actually has data now what's interesting now is let's actually go to our database and add a new product so i'm going to just import a json i created before which just adds one product to this list so you don't have to watch me create a product here i'm going to import and i guess you can see we have added this fifth product to our database now watch what happens when i resume back on this application tab boom you can see that's fifth product is already added there and that is the use swr revalidation on focus in action now when we build our application we only have four products so when we view the page source there is only going to be the first four products but then between the time that we built and deployed our application our data actually changed then we're fetching that change and update on the client side using swr which makes it pretty easy let's summarize we looked at client-side data fetching index.js applications and we learned that it isn't any different with the standard react apps we actually started using react hooks like user state use effect and the native feature api to fetch products and show it on our page we then did the same thing using a third-party package called swdr which makes client-side data fetching easier and it comes with some built-in features at the end we combined next gss static site generation with client-side data fetching and the idea was to build our sites aesthetically but then fetch any updates on the client side that's it for me folks i hope you learned something in this video and i will see you in the next one bye-bye
Info
Channel: Hamed Bahram
Views: 2,044
Rating: undefined out of 5
Keywords:
Id: l8icUH4siX4
Channel Id: undefined
Length: 18min 14sec (1094 seconds)
Published: Fri Jun 03 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.