Next.js 13 Data Fetching - The Ultimate Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up YouTube my name is Brett and today I'm going to teach you guys how to do data fetching inside of next js13's app router so you're going to learn everything you need to learn to fetch data using next.js13 but also before we get started if you could hit that like button and also subscribe for more content just like this that would be greatly appreciated but let's just jump right into it so before we get started with the actual coding we are going to go over the next js13 docs using the app router so make sure this is selected as using App router here at the top left so I'm inside the data fetching section and they give us four main recommendations when fetching data so we're going to go over them really quickly so number one is we should fetch data on this server using server components so by default next js13 all the pages the files the layouts are server side rendered so the only time a page isn't server side rendered is if you mark the top of the page with the string sing use client and the only reason why you're a market page with a used client is because there's interactivity on the page or you're using a react hook like you state or use effect the second recommendation next.js offers us is that we should fetch data in parallel to minimize waterfalls and reduce loading times so that means it's going to fetch two separate endpoints at the same time and this will make sure that the data loads at the same time while reducing the time it takes to actually load the data the third recommendation is for layouts and Pages we should fetch data words use reason being is next.js will automatically dedupe the requests in a tree this means after we recall a fetch request the first time it will automatically cache the request inside of a temporary cache and this will make it easier for us to actually fetch the data next time we need it so whenever we need to fetch data you should always call it where needed because it will be stored in a temporary cache that is easily and readily available so now that we've gone over the four main recommendations for fetching data let's open up our terminal so we can actually create our next js13 project so I am going to go on my Windows desktop and I'm going to open up my terminal I am going to change directories into where I keep all of my code and you should do the same thing and then we are going to run the command npx create Dash next Dash app at latest this will prompt us to a few questions that we need to answer to start our project first one is what is the project name I'm going to say data fetching video we're not going to use typescript so no node es Flint yes to tail and CSS no to the source directory yes to the app router and know to customize the default import alias it's going to initialize the project and it's also going to install all the dependencies necessary for the project this should take about 15 seconds and then after this is completed we can change directories back into the project that we named it which is data fetching video and then you can type code Dot and this will open up my vs code editor which is my text editor and you could close the terminal as well and now we are ready to actually start coding but before we actually start doing any code let's clean up some files to make sure everything is ready to work so inside of the app directory we're going to go inside the global CSS and we will remove lines 5-27 and leave lines one through three since we will use Tailwind CSS to style a few things the layout.js file is totally fine we can leave it as is and then the page.js which is your home page we can remove everything inside the return and then we will have a div and then inside the div Let's do an H1 saying home and we can remove this import of image at the top okay so everything is set and ready to go but before we go and do that I'm going to show you where we are going to fetch data from so the website is called dog.co forward slash dog Dash API forward slash so what this does is it's a pretty much a dummy data fetch practice that we could use the fetch data here's the fetch request and every time we click the button it will fetch a new image of a dog and there is a specific reason why I'm using this API later on in the tour we're going to use a different API called the Json placeholder you've probably seen it from other YouTubers and different tutorials it's a very useful API dummy data as well for the internet but we are going to use this API for our first fetch request which we are going to fetch data on our server component so when making fetch requests you do want to organize your code inside different directories like utils folder where all your functions should be but for this specific API call to the dog API we are going to call this in the home page because we are going to use like I said the Json placeholder API in a little bit so like I said before too every page is server side rendered and we could actually call the fetch request inside of the page but before we do that let's run the development server so you're gonna do an npn rundev it's going to open up on localhost 3000 and all I should say on our page is the H1 that says home it's here at the top left so let's just style this a little bit before we get started we are using tail1css so we'll put the text Center and the H1 let's have a class name of text 5xl font bold and let's give some margin top as well of 20. so let's just look at it real quick and we have home right there cool so now let's make a fetch request to this endpoint so let's copy this endpoint and let's create our function up here in the function we will call we'll call it git dog get dogs because that is what we're doing so it's going to be async function and it's going to call get dogs and the first thing we are going to do is we are going to create a variable called response because we want the response and the response is going to await a fetch to that endpoint that I copied and it's going to be inside of a string so copied a little more than I wanted but there is the right endpoint URL and after we get the response we need to create it as a Json so we're going to await the response as a DOT Json and we'll store it in the data variable and then we could return as data and then down here we could just actually call that function so we could say cons dogs equal a weight get dogs and then call a function and then this has to be an async function because we're awaiting some data so now we could use dogs inside of our jsx down here below the return and before we do that we could actually just do a console log so we can actually console log dogs and see what we get and since it is the server-side page it's going to show up inside of our actual terminal here in our code so as you can see here we get a message and the message is the image and the status is success and that we get requests of 200. Okay cool so what that means that is working and we are actually retrieving dog images like I said below the H1 we could do a image tag and if we do an image tag this is a component inside of an xjs we need to import at the top from next last image this takes in a few properties so the source is going to be dogs Dot message and the reason why is because if you look at the console that we got right here it says the message and the message is the actual um image URL so that's why it's dog stop message and then we must give it a width and a height and then we must give it an alt and the alt could just be dogs and then let's give it another property called priority okay so I'm just going to show you what it's going to show me it's going to throw an error and I'll explain why so if we go to our locals 3000 we get an error because we are trying to fetch a image from this URL and it's pretty much telling us that it's not configured inside of our next.config.js file and it's pretty much like we don't trust this source and if you do trust the source put this in your next doc config.js file so let's go back to our code we go to the next doc config file inside of the object we are going to say images and then inside that we'll have an object with domains and the domains there'll be an array with the string and it should be images dot dog dot CEO so that is the URL we are fetching images.co perfect and then we can just put a comma behind this and then let's just run our server again so npn rundev we will open up localhost 3000 and then since we are fetching the data with image with the image component now we get a dog so now we're actually fetching data successfully but the main reason why I wanted to fetch data from this dog API is because technically if you go back to the API every time you fetch data it gives you a new dog so then if we refresh our page here we get the same dog so you would think the API isn't working or your code isn't working but if you look at the next JS docs every fetch request is cached inside of a temporary cache and it just keeps fetching that same data so that means we need to give an option to our fetch request saying we don't want you to store the data in a cached folder and we want to get new data endpoints every time like new data so we could close this config file and it is very simple to do so right behind the fetch endpoint we are going to have an object and inside the object we will have a cache and we're just going to say the cache we want it to be no cash so this means every time we do not want to Cache the actual data and we want to fetch a new response every time so let's now refresh the page and we get a new dog every time so that is a very specific easy point to get around when fetching data but like you said every fetch request stores data in a temporary cache so you need to make sure if you don't want it stored you need to have the option that says no cash so let's clean up our code a little bit and let's remove all the dog API because we don't need any more so we can remove the initialization of the function remove the actual function itself remove the image and remove the end port okay so now let's start actually um organizing our project so we could actually start using the Json placeholder API so I know we are going to use the user's API endpoint inside of the dummy data so I am right here going to have a link component from next slash link so we have to import at the top and we are going to go to a users page which we have not created yet and we'll create right now so we're going to say go to users and then let's do a closing tag of the link to close it and then let's create this user's segment right here inside of our app folder so all you have to do is create a new folder inside the app directory and we must call it users because that will be the path name and then inside the path name we need a page.jsx file or TSX file whatever you're using and then we can do RFC and if you don't know what the RFC is these are Snippets and they are done by the extension es7 so all you have to do is download the es7 snippet right here and you will be able to type code faster and more efficiently we could also change the function name from page to users page because that is what we are doing on this page and we can keep this as page for now and we could go back to our actual localhost 3000 click go to users and as you can see we're on the users page and it just says page Okay cool so let's dial this page a little bit more let's just put users as H1 the parent div we'll have text Center margin top 20. the users will be a text of 5xl and font bold okay so now let's go to Google Chrome and let's get out of the dog API and let's just type in Json placeholder so it should be the first saw it's called typico.com and it is a free fake rest API and if you scroll down when we get on the page you will be able to see the resources that we could actually request from so these are endpoints we could request from it could either be post comments albums photos to Do's or users like I said we are going to use the user's endpoint and it should give us back 10 different users in Json format so if you click it we get users with different properties like name username email address and much more and there's 10 of them so what we're going to do is we're going to copy this endpoint which is where we want to fetch the request from and we just have it now ready to go and like I said now we want to create a function so we could use it inside of the users page so we are going to organize this a little better and inside of the app we are just going to create a Labs folder and this is where all of our functions are going to be so the first one is going to say get users Dot jsx we could do react functional component and then it could just be called Gay users that's perfect so inside of this code block we want to get a response from that awaited phage data and since we're using a weight this must be an asynchronous function we were going to fetch the data from that endpoint we just copied from Json placeholder which is that right there and then we need to do a check to see if we're actually getting response so we're going to say if the response is not okay we should throw a new error and stop the code right away saying fail to fetch users and then if we pass that check we need to return the response as a Json so right here is our code and what we're fetching is static data on a server component so the reason why it's static is because there's always going to be 10 users every time we fetch it so we can store it in our temporary cache so we don't need any options behind this so next we do want to go to the users page which we created here and we actually want to import that function from the libs get users.jsx file so we're going to import get users from Libs get users and now we just need to call the function inside of the user's page so we're going to hook it up to a user's variable and we're going to wait the get users and then we got to turn the function to asynchronous perfect now after we have the H1 sync users right below that so we can make sure we're fetching the users we want to map through all the users so we're going to say users .map and then we're going to say each user we want to return and then we need a div which the div is going to be the parent div or we could do empty fragment and then inside of this we could have a P tag and then the P tag needs a key since we're mapping through everything and the key need to be unique which will be user.id and then inside of the user.id we could just display the user's name and then we could close we should be able to close this and this okay so now everything is closed and ready to go we're mapping through all the users and all we're returning is the user.name so we could check out the code real quick on our Local Host and it's saying users is not defined it's because I named a user and not users so let's look at it again and then as you can see here we get all of the users from that fetch API endpoint so now that we successfully fetched all of the users I did style it up a little bit so before I say that let me show you what I did I just added on the P tag with the key a class name of text 3XL and a margin top of 10. so now that we have successfully fetched all of the users we want to fetch the specific information for each user when we click on it so that means we have to fetch Dynamic data and the way you fetch Dynamic data inside of next js13 is inside of a folder there needs to be another folder and this folder is going to be in bracket notation so we need brackets and whatever side what is ever inside of the brackets that is going to be the prams so the parameters that we pass to that specific page so for me the parameters have to be unique and they're only custom to that specific user so I'm going to use ID so as you can see there the parameter we use is ID and then this Dynamic page needs to have a page.jsx so now we can actually fetch Dynamic data and display it on this Dynamic route so we have to fetch each individual user and the way we are going to do that is if we go back to our jsonplaceholder.com as you can see here if we go to say slash users the pram we could do like ID of three and that should give us the third user so slash user slash three so this number is dynamic and is always changing so it might be seven if we click seven it could be six it could be ten it could be whatever number so that number could always be changing so we have to fetch the data dynamically so I'm going to show you exactly how to do that so I'm just going to copy this this will be our endpoint for our Dynamic fetch and we must create another function and where we're going to create this function is in our lives folder and we are going to call this get user .jsx and we're just getting one user and what we're going to do here is we have to export default you know be an async function called get user and we're going to pass in the ID into this function so what we're going to do here is we're going to get a response and this is going to be from the fetch request and since we know it's Dynamic data data we need to use the template literal so that means back ticks instead of strings and inside of that we could paste that URL and like I said it's not always going to be seven it could be anything from 1 through 10. so we need the money sign and then brackets and then the param which is ID that we're passing in so this could be dynamically changing now let's check to see if the response is okay because if it's not okay let's just stop the code and throw an error saying that we failed to fetch the user so that means we know that this endpoint didn't work and we know where the problem occurred and so then right below that let's just return the response as a Json and then let's close the code with one more bracket okay so this is our get user function inside of our lips folder so we are exporting this because we need to import it inside of our Dynamic route which is the bracket with the ID so let's import that so we're going to say import the get user function from the libs slash get user okay so let's display their information so we're going to create a async function called the user page and we have to pass in the params inside of this page like this so we're going to destructure it and we're going to say params and the prams is going to be destructed into the ID because that is what we defined here inside of the brackets so now we're passing the param successfully what we need to do now is we need to actually call the function get user so to do that we can name this user data and this will await the get user passing in the ID okay so now we could just re use the return and start writing some jsx and inside the return we could have a parent div that wraps everything and inside of this we could just give this an H1 that says user data dot name because that is going to be the data name and then let's close the whole code block with this block right here so let's test everything out to make sure everything's working correctly and we're actually getting data dynamically so let me go back to the home page we're on a little close 3000 we click go to users and then we get all the users now if we click well actually We're not gonna be able to click anything because we need to make them clickable so we have to go back to the users page not the dynamic page but the actual slash users and as you can see here the P tag there's no link to it so we need to actually surround the P tag or inside the P tag with a link so we can do it inside and we need the link component and we need to import at the top and then we need an href that is going to be a dynamic route to slash users slash user dot ID and then we just need to close the link tag so we can actually navigate to that page so whatever name they click on it's going to give us the ID and then it's going to show us that information again so let's go back to our page we'll go to localhost 3000 go to users and if we click say Chelsea Dietrich as you can see here it says Chelsea Dietrich so let's try to make sure it works let's click Urban see it says Irvin Howe Leanne it says Leanne Graham so we are going on Dynamic pages and if you do click it you see clear map Bosch and it says here the URL slash user slash three and the only reason why it's showing the name is because if we go to our Dynamic page all we are displaying in the is userdata.name as H1 so bang that is how you do Dynamic data fetching inside next js13 zap router next thing I want to show you is I want to show you how you guys can fetch data in parallel to fetch data in parallel we want to fetch data from two different endpoints at the same time and this like says in the docs it will help reduce the load times but it also show both data endpoints at the same time which can actually cause a problem because maybe if somebody's computer is slower you won't see that data until both actual endpoints are resolved the promise so let's go back to our type ecode.com and if we go back to our resources and routes I want to get the users post for each individual user so we need to actually fetch that dynamically as well and this time it's going to be a different URL so as you can see here this request right here this get is getting the post ID which equals one so we're going to have the user ID so it's going to be slash post slash user ID no slash post question mark post user ID equals and then the dynamic data I'll show you exactly how it's written out I don't know if I explained that the best but let's call a function one more time so like I said this function is going to call the post for each individual user and we want to fetch this data in parallel with the user data so let's create another function which we will call get user post Dot jsx and then this get user post like what it says we are getting the user post so we're going to export default async function and we will call this get user post we are going to pass and the ID as a param and then inside of this code we are going to set a response equal to the weight and then actually as you can see here my GitHub co-pilot actually correctly coded it so that we're going to fetch it from the Json placeholder.typeecode.com post and then the parameter is we're going to get the post of the specific ID that is dynamically passed in of the user ID so that is the end point we are fetching from and then we need to do a check so if the response is not okay we're going to say we failed to fetch the user post and we know the end point we're trying to fetch from isn't working so then let's return the response.json okay so this is the get users post function that's fetching Dynamic data of every user's post so we are exporting it so we do need to import it inside of our parameter segment of our page jsx file so we're going to import it here at the top so we're going to import git user post from the libs and then like I said we want to call this data in parallel so I'm going to remove this H1 and I'm just going to say an H1 user information for now and we can remove this because I'm going to show you how to fetch in parallel okay so we have both functions imported at the top the next thing we want to do is we want to initiate both request in parallel so we're not going to await the data we just want to make sure the data gets initiated at the same time so the first one was called user data and that was equal to the get user passing in the param of ID and the next one we could call user post and it'll say the get user post passing in the pram of ID to that function next we need to do a promise dot all so we're going to wait for both requests to complete and we're going to call them at the same time with the destructor destructuring of the user data and user posts so it's going to look like this we're going to have a user and we're going to have a post and then we're going to wait the promise for all of the user data and user posts and we're going to give it to these individual variables so now we are fetching data in parallel because we're fetching them at the same time so that is how you do it I could show you exactly in action so we could have a p-taxing username and then we can map through the post if we want so let's just do that real quick so we're going to say post.map we're going to have return and then inside the return we're going to have a key we'll have to post title and close the P tag and that's good enough for now because I just want to show the data because we're going to change this up real soon here and then right behind this div we're missing something here okay so now let's check our localhost 3000 and let's go back to localhost 3000 the home page we go to users fetching all the users we click Patricia and as you can see it says user information because that's your H1 we have Patricia and then we have all of the post titles which obviously is dummy data it doesn't make any sense but we are displaying everything and as you can see it loads so quick as my computer is pretty fast that the data loads at the same time and if it both of the requests aren't fulfilled yet it's going to wait for the other request to fulfill so there is something we can do to make it a lot easier because like I said some people's computers are slower so the post which is a bigger request to request from like more data it's requesting might take longer to load in than the name so the reason why we should use a suspense like a react suspense or a loading state is because we want to show the user a good experience and make sure that they know hey there's more data coming in it's just loading so what I'm going to do here is we are going to change this parallel fetching and we're going to use react suspense so before we use react suspense I want to make my data replicate a slow computer so to do that I want to make sure that the user post comes in later than the actual other data that I'm I'm going to call which is the user information so right above here I'm going to have an await and it'll be a new promise and then I am going to set a timeout to this new promise like doing this in parentheses too so what I'm going to do here is I'm going to have a delay of three seconds so that's why I put 3000. so we're going to delay this data for three seconds and I don't think I removed anything yet yep so we are fetching data in parallel so I'm going to show you that all the data is going to take like three seconds to load so let's try it again should we have Chelsea Dietrich and as you can see it's taking longer to load I don't know if you could tell like one two three so I click it one two three so as you can see it's taken a little longer to load because it's not going to load and show the information until all the data is loaded and this isn't a good user experience so we need to do is we need to add the suspense like I said so we need to import suspense inside of our Dynamic page at the top it's in curly braces with the capital s and we set a timeout of three seconds to the user post so what we are going to do here is we are going to remove this promise not all and we could just call the first function which is a weight user data which is the user's data we're calling a user so this information the user.name will display but we aren't awaiting the data for the posts so we're going to get an error thrown so what I am going to do here is I'm going to create a component called user post and what we are going to pass is a promise and this is going to equal the user post and this is a component which we haven't created which we'll create right now in a components folder so create a components folder and then a file called user we could do a capital user post .jsx RFC it's called user post and then we are going to all we're going to do here is we're going to map through the information like we did there and then we have to pass in the parameter which we're passing in as a promise which is user post and we're passing it as the value promise so we must accept the promise up here and then we can say cons post equals await the promise and then what we could do here is we could pass through and map through all of the posts and display them so I just copied and pasted real quick here and as you can see here we're mapping through all the posts we have a key of post ID we're showing the post title and the post body so now on the dynamic page with the brackets ID we must import that component in here so it is called user post from component slash user post so what I want to do is I want to wrap the user post in suspense and that means that is going to have a fallback of a loading and the loading fallback we could just do a P tag thing loading so if the information doesn't display yet it's just going to show A P tag saying loading and we could just do like a class name of text Center and we could just do text 5 XL cool okay and I did like I remember I put a three second delay on the user post which the reason why is because we are getting the user post right we are passing into the variable user post and then we're passing the user post into the Promised variable and then using it here so let's look at our code and we have a issue right here a weight isn't allowed in a non-async function so I forgot to put this function as async because we're using awake okay so now when we go to our users localhost we go to all of our users we fetch all the users when I click a person's name we should see loading stay like this three seconds and then we get all of the information so that is how react suspense works if there is no data fetched it will show the fallback of whatever you want to put you could put a component you could put a P tag in H1 you could put whatever you want so we could go back to the code just so you guys can see it again real quick do what it looks like all you do is wrap the component or the code with a suspense because if that code doesn't load in time the suspense will take a place and it will use the fallback and as you can see here they get requests for user seven took 3059 milliseconds which is three seconds so that is pretty much everything you need to know about next js13 and data fetching within it let's go back over a few of the docs real quick I do highly recommend you go over the docs yourself so you can learn more about next js13 in general and also the data fetching but if you do have any questions hit if you have any questions comment them down below inside of the comments section and I will get back to you within hopefully 24 hours to answer anything and in the meantime if you have a question that needs answered and I'm not getting back to you quick enough like I said revisit the docs the docs are very very helpful and easy to understand but other than that I hope you enjoyed this video I hoped I helped you a lot with your learning and understanding of nexjs 13th data fetching and with that said if you can hit that like button and also subscribe for more content just like this I would greatly appreciate it so happy coding to all and have a great day
Info
Channel: Brett Westwood - Software Engineer
Views: 1,661
Rating: undefined out of 5
Keywords: nextjs, next js, next js tutorial, nextjs 13, nextjs tutorial, react, next.js data fetching, fetching data in nextjs, how to fetch data with nextjs 13, nextjs 13 data fetching, server side data fetching, react suspense, dynamic data fetching, nextjs tutorial 2023, next js 13 tutorial, next js 13 app directory, nextjs 13 data fetch, react data fetching, fetch web api, http request javascript, cache nextjs 13, revalidate nextjs 13, parallel data fetching, next.js tutorial
Id: -Sj05H2AuW8
Channel Id: undefined
Length: 40min 7sec (2407 seconds)
Published: Tue Jun 13 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.