Create Pages & Fetch Data in Next.js Using Static & Dynamic Routes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey team we're gonna learn how to create pages in next.js including static pages and dynamic pages using all the nexujs data fetching methods like get static props get server-side props and get static paths i'm colby feyhawk and if this is your first time here make sure you hit subscribe and that little bell icon to make sure you get notified on future tutorials starting off if you're not familiar next js is a react framework that comes with a lot of awesome features built on top of react including things like routing and data fetching and things that make it a great way to build applications or websites now one of the features is pages where it uses file system routing where we're able to easily create whatever route we want to do by just creating that file inside of the pages directory on top of page creation we have things like dynamic routes where we can take a parameter as an argument right inside of that route so that we can create our one file to have a variety of pages with that same kind of context and on top of that we have a variety of options for data fetching for those pages where we have get static props which helps us fetch data at build time as we see here you have get static paths which help us actually determine what pages are going to get built to pass in those props and then finally we have get server side props which provides us ssr or server side rendering so that we can make sure that each request to the server for the page is going to be dynamic and that request will happen on the server so to bring this all together we're going to work through a couple practical examples where we'll step through things like creating a basic static page with no data then we'll create a static page where we're going to fetch that data using get static props at compile time and then finally we'll create a server side page where we're going to have that dynamic request every single time that page actually reloads so to actually get started with our next.js application we're going to use create next app which allows us to easily spin up a new application and start diving right in we're also going to use the last airbender api which is just a fun way for us to have dynamic data to work with when we're actually making these requests to create all of our pages so to get started inside of my terminal i'm going to run yarn create next app and i'm going to call that my last airbender wiki what that's going to do is in the background it's going to clone down the default next.js project it's going to install all the dependencies and even reset git to make sure that we're able to start off running but once that's done i can cd into my new directory and i can run yarndev which is going to spin up a local development server where i can open that up right inside of my browser and nextjs will start going away to actually compile the pages that are existing inside of that default template where now we can see that i have my default nexjs application now starting to actually just poke around inside of this application we can see we already have this pages directory where inside we have a few files where importantly what we want to look at is this index.js where this index.js is going to be our home page which is exactly that page that we just saw where it's pretty much a simple react component where it's going to include all the content that we want and it's going to provide us ways that we can actually provide dynamic fetching methods which we'll see shortly here now if i instead wanted to create my own new page as i mentioned earlier it uses file system based routing so right side of pages i'm going to create a new file called about.js and let's say we're going to export a default function and we're going to call that function about or inside i'm going to simply return a div where inside of that div let's call an h1 and we'll say about this wiki now this is a really simple option and we're not going to spend a lot of time on actually styling this because the point here is just to show how the actual page creation works but if we go to our browser and we go to the about page we can see that next js is going to load that page and we see our about this wiki so not only do we want to create a static page like this we want to also pull in some dynamic data into that page so i'm going to create a new file and i'm just going to simply duplicate this existing one because it's also going to be a similar base file but i'm going to call this avatars.js where inside let's first update that function name avatars and inside i'm going to say that i want this to be my avatar's header where inside i'm going to simply display a list of avatars including aang but i want to do so dynamically so that i can make sure i'm pulling in all the avatars for my api now to start off the way that we're going to fetch the data inside of nextjs is we're going to use the get static props function and to do that underneath our function let's say export async function get static props and inside we're ultimately going to return an object where that object has a props property where we're going to be able to define any of our data for that function the great thing is now that we have this get static props function we can add any kind of request we want right inside where it's ultimately going to take that data and we're going to return it inside of this props object which we're going to be able to make available for our component here now i know that this is a little bit hard to read but we want to look for the avatar route where we're going to be able to get all of our avatars and we can even open this up in an example where we can see exactly that endpoint getting hit where we have an array with objects of a bunch of our different avatars throughout the different series so inside of my get static props function i'm going to say constant avatars and i'm going to say i want to await the fetch function where inside of fetch i'm going to pass in that avatar's endpoint including the domain along with the path to that endpoint well ultimately we have access to the fetch api because next.js actually polyfills that whenever it's not available including on inside of node where this data is going to get fetched but finally i'm also going to chain on a then command where i'm going to pass in the response and simply say that i want to take that response and send it to jason so that way our avatars is actually array of data that we'll be able to use now before we even pass this in as a prop we can take this avatars and we can console log it right inside of this function so now instead of this about page if we go to avatars we'll see that we have our page where currently we only have aang because we only have that static list but if we look inside of our terminal because that data fetching is happening on node inside of node we can see all that data being logged right inside of our terminal so now i can pass in my avatars right inside as a prop where inside of my actual component for my avatars page i'm going to now make that available so we can see here that those props correlate to the actual props inside of my page component where now instead of just simply listing out aang just by himself i'm going to now take those avatars i'm going to map through each avatar where i'm going to say that i want to return a list item with that avatar.name and close that list item but then also because we're in react we want to make sure we provide a key on each of those fields and in this instance it's going to be avatar dot underscore id but now we can also get rid of that static eng and once we reload the page we can see that we're now dynamically filling up that entire list with all the avatars that we've seen throughout the series and just for a quick review what we were able to do is not only set up a new page where we can contain all of our avatars we were able to take this get static props function which allowed us to actually make a request to that api fetch all that data turn it into json put it inside of an avatar's constant and actually make it available as a prop where this page because we're using git static props is going to be statically compiled with all that data as opposed to actually being server side rendered where it's going to send all that html with the first request now this is great where we're able to easily get that list of data and actually iterate through it but what if we wanted to create a new page for every single character inside of the avatar ecosystem so for this example we're going to use the characters api so inside of pages i'm going to create a directory where i'm going to call that directory characters and inside to start i'm going to call that file quora.js now like before we can simply grab our about page or whatever we want and we can add our quora here where let's say that we're going to fill in her name of korra and while this alone looks like a completely static page with it which it is we're going to learn how we can transform this into a dynamic route so to start when building chorus page i don't want to have to statically add her name inside of each one instead i want this to be a character template so i'm going to first rename that component to character where we're going to dynamically fill in this data now to actually look up cora's information we're going to use this endpoint where we can search on the character's name and just a quick note it's not the perfect way of doing this because using search as a way of getting that character isn't an exact identifier and it can come with unexpected results but just for the sake of this example we're going to use this because it's an easy way for us to be able to navigate to the pages to see how this actually works so here if we open up an example we can see similar before that we're going to actually get that payload with the request but let's see if we search for quora we can see that we get cora's actual actual result here so to start let's copy that url and like we did in the last example we're going to start off by exporting a new async function called getstatic props what we're going to do inside is we're going to create new content but this one we're going to call results because if we saw before with the search we're going to be given an array that's going to be returned where for this we're going to use the first result of that array so i'm going to say i want to set that equal to a weight where i'm going to use fetch just like before and then i'm going to chain on my then where i'm going to take the response and turn that response into jason but then finally on the next line i'm going to say that i want to return my props where inside i'm going to say that i want my character to be results in that zero index to get that first character now like before we now will have that character data available so i'm going to make that as a prop inside of my character page here where i can now change that h1 to character.name but now if i go to slash characters slash cora we can see that we now get core's name and we're doing that dynamically now just as a quick note of something that i didn't mention before if we saw before we created that avatar's path where that's going to be slash avatars but we just saw here that we created a nested route meaning we created a directory with a file inside of it so now that's going to be equal to characters slash quora when we actually visit the path now inside we also have some additional data so why don't we make this a little bit more fun and let's add the image and maybe even the affiliation so above my h1 i'm going to add an image and i'm going to say i want the source to be equal to character dot photo url which is that property that we just saw and we want to always add an alt which for this case it's going to be the same as the character name so there's and we don't have the context of the photo itself so we can just leave that empty but then finally maybe we can add the affiliation we're underneath my header i'm gonna say i'm gonna add a paragraph tag and i want my affiliation to be character dot affiliation and now as soon as the page refreshes we can see we have our picture of quora we have our name still and we have that affiliation all being dynamically added from git static props now this is really great but we want to be able to do this for any characters for example i want to be able to go to slash aang character slash aang and be able to get ang there or really suki or abba or anybody else from this show so this is where get static paths and dynamic routes come in where we're going to be able to take a list of all the different characters we want to make available to tell next year's that we want all those characters to have pages individually for them inside of get static paths and we're going to set up this route to be dynamic so that we can pass that id or the name in as a parameter for us to actually make this search request for inside of git static props so to start we're going to use the characters endpoint so that we can get all characters but by default it only has 20 per page so we're also going to tack on an additional parameter for per page where if we look at the example here we can see that it opens up where this one has per page of 10. i'm going to change that to 500 because there's slightly under 500 characters but that way we can have a page for every single character but now i'm going to copy that url and back inside my code i'm going to now export a new async function below get static props and i'm going to call that get static paths where this is going to function very similar to get static props except we're going to create an array of paths instead of passing in the props themselves so the first thing i'm going to do is i want to get all the characters so i'm going to say constant characters is equal to await fetch i'm going to pass in that url that we just saw for the 500 characters and then just like before i'm going to tack on my then i'm going to say i want it to turn into json so next instead of returning props we're going to return paths so i'm going to say return our new object and inside that i'm going to determine that i'm going to want to define my paths where i'm going to want to map through this character's array so i'm going to say characters.map and then for each character i want to return a new object configuration where inside of that i want to define my params which is going to be those dynamic values that we're able to get from the path where in this case we're going to set it up to be character id so that we can actually specify what that character id is going to be and in this instance let's call it character character.name now when we're actually setting up this parameter we need to make sure that we're providing it as a parameter inside of the actual file for our routing so in this case we want to change quora instead of the name directly we're going to use brackets and we're going to wrap character id with those brackets because we're telling nexjs that we want that to be a dynamic value where we can see that the character id as our param is going to be the param inside of this file name and ultimately our page route so what's going to happen is nexjs is going to use get static paths see that this is an actual dynamic route and it's going to say it's going to loop through all these paths and it's going to know that we have this dynamic parameter and for this we're setting what that's going to be for each one so it knows ahead of time which different routes to actually render now as one last thing we have to also define a fallback value here on this getstaticpath's return object which is going to say whether or not we want to handle the situation where the parameter is not found and in this case let's just say that we want a 404 or say it's not found if we don't have one so we're going to say fallback is false but next once an xjs goes through all these paths and try to render the page we're going to be able to run get static props for each page where that's going to ultimately take in the params that we'll use to fetch that dynamic data so inside of this function we're going to destructure an argument called params where with my params i'm going to be able to get that same character id value from that object because that correlates directly one-to-one when i'm passing in those dynamic parameters so i'm gonna first turn this into a template literal statement for my actual url so that at the end here instead of passing in name as quora i can say that i want to pass in a variable that's going to be params.character id so now if i refresh the page for quora we can see that it's actually not existing now if we look at the url here we can see that we're passing in quora with a lowercase k and that's going to be the issue because if we look inside the data the name value is actually an uppercase k and now if the if we try to go to that url inside of chrome right here it's not going to actually refresh the page but if we go to localhost 3000 slash characters and we actually go to a new page with the uppercase k we can see that it is going to indeed find quora now we have ways to actually start fixing this inside of our code first of all we can normalize our values our character ids that we're passing through so for instance if i want to make sure that that core is always with a lowercase k i can say that i'm going to create my character id where i'm going to set that equal to character.net lowercase and then i can pass in that character id right as is right into the params object but now once my original core page loads we can see that it's working just as expected again we can even see that this works just the same if we change this to ang or if we change this to appa or suki or whatever character we want now the only trick here though is we're using single word names here now if we wanted to see someone like cabbage merchant we can see that inside the url it's getting parsed as a percent 20 which is the encoded version of a space meaning we're still seeing that it's working but that's not necessarily a normal term or normal url that we'd want to see so we can also fix that so with our character name not only can we set it to go to lowercase we can also say that we want to replace any instance of a space where this is going to be a regex value and we want to set it g to make that a global regex value and we're going to replace that with a dash so when xjs actually goes through and gets all that character data and turns it into a list of params it's instead going to see cabbage hyphen merchant now the only trick here is that params value here is going to include that dash and the api in that search isn't going to recognize that dash so the last thing that we only need to do is replace those dashes back with something the api will actually understand and that'll be the plus sign so we can say on the params.character id i'm going to perform a similar replace where i'm going to use the slash and i'm going to actually escape that hyphen so that i can say i want to replace all those with a plus sign because the api will understand that and i want to make sure i do that globally but now if we actually replace that percent 20 with a hyphen we can see that we can go to cabbage hyphen merchant and it works perfectly well it was able to find that and request all the data for that character so in this example not only were we able to create our static page we were able to dynamically fetch data for that page but we were also able to dynamically create a wide variety of paths so that we can make a bunch of different pages available for next yes to create not just one single file but by using dynamic routes we can now visit any character we want as a character path now finally what we did so far was all static where these are statically generated pages that are going to be html that serve to the person who's actually visiting the site that way there's not going to be a request that actually happens when they visit that page in the browser it's all going to be static but next.js also supports the ability to have server-side rendering meaning when i go to a page in the browser it's going to go to the server render that request and return it back to the browser so for this example let's use the affiliations endpoint where i'm going to say that i want to be able to go to a page similar that we did for characters but i want to pass in an affiliation id so that i can go see all the characters that are under that particular affiliation so to start i'm going to create a new directory called affiliations and similar to what we did with character id i'm going to create a new file and i'm going to say that i want this to be a dynamic value and i'm going to say i want that to be affiliation id instead dot js now because this is ultimately going to be a list of characters i'm going to borrow our avatars request that we did before i'm going to simply grab that page itself and i'm going to rename that to affiliations and let's say instead of avatars they're going to be characters that we're going to be able to map through and i want to say that i want my affiliation matching whatever we're going to pass in as the id so i'm going to say affiliation matching and we're going to pass in that idea later but once inside the characters array i want to make sure that i also update the avatar to my character so if we're imagining how this works it's going to be very similar to the character id where we have this dynamic route and we want to hit a specific route such as slash affiliation water tribe where we're able to get all the characters from that tribe so what we're going to do is we're going to export a new async function and this time it's going to be called get server side props now this function is going to work similar to get static props where we're going to return an object ultimately that has props with all of our data now like before we want to make sure we get that endpoint so i'm going to open up the example and we can see here that we have this affiliation endpoint where we're going to ultimately pass the name in as the parameter instead of the character id like we saw before so inside i want to say i want my constant characters to equal away fetch where i'm going to pass in that url and again i'm going to say then where i'm going to take my response and turn it into json make sure you get the period now the biggest difference here between get server-side props and the static methods is we don't have to use two separate functions we can use this single server-side props function because we're getting that parameter dynamically on the server so just like we did inside of get static props i can say that i want to grab my params now like we did inside of the character id i'm going to create a constant called affiliation id where i'm going to set that equal to params.affiliationid where just like we did inside it get static props i'm going to say i want to replace i'm going to replace a regex where i'm going to replace all the hyphens because again we want to bring those params inside as something that's url friendly and we don't want to do that globally and we're going to replace it with the plus sign so that it's search friendly inside of that url but ultimately because it's happening on the server again we can get that affiliation id straight from this method turn it into our id and we're going to now pass it into this url so here i'm going to change this like before to the template literal where i can now change this value to a dynamic variable that's going to be my affiliation id and then additionally i'm going to pass both the characters and my affiliation id inside as props so i can take my characters which are already set to map out along with my affiliation id so i can add that i'm going to have my affiliation matching that value but now if i go to slash affiliations water we can see that it's going to load up and i can see all the characters that match that i can even grab all that other metadata from inside of the original character where i can paste that in right inside of my list item and we shouldn't have multiple h1 so i'll make that h2 but we can now see that we have our affiliation matching water and we have pictures and the name and the affiliation of all of our different characters so just a quick review we can see that this worked very similar to get static props and get static paths except we only needed to use this one function but that's because what's happening is when the server actually sees that request to that specific route it's going to say hey i'm going to take that parameter and i'm going to pass it right into this function and we can see if we can actually make that data available we can even see that we're not actually pre-determining this id of water because we can really now use this url as a search method where we can even go to something like northern water tribe where if we load that we now only see the result for the the northern water tribe i can even change that to my southern water tribe where similarly it's going to filter only the people who are related to that tribe but the great thing about nextgs we have a ton of options for how we can actually fetch our data and the great thing is we can mix and match and if we have one page that we want server side rendered and we have others that need to be completely static we have the ability to do that for through our different pages whether we're using guest server-side props or get static props and paths or if we're just creating a static page without any additional data fetching one of the things that makes next.js so powerful is its flexibility with data fetching and page creation where we can be just as dynamic we want and we can also be just as static as we want have you seen any crazy examples or really great use cases for using dynamic routes or even static routes let me know in the comments if you want to learn more about what i actually mean when i say static generation or ssg check out my video which you can see the link above for what is ssg or if you want to take this dynamic values to another level where you can use those dynamic values to create your page seo metadata check out this video react seo with nextgs using the link above if you like this video make sure you hit thumbs up subscribe for future updates and hit that little bell icon to make sure you get notifications for my next tutorial thanks for watching
Info
Channel: Colby Fayock
Views: 842
Rating: 5 out of 5
Keywords: nextjs, next js jamstack, next js, next js tutorial, create next js app, create next js, create next js react app, next js page, next js pages, nextjs dynamic pages, nextjs dynamic page, nextjs dynamic page title, nextjs static, nextjs static routing, getserversideprops, getstaticprops, getstaticpaths, nextjs data, nextjs data fetching, nextjs ssg, nextjs ssr, next js ssr vs ssg, next js ssr tutorial, next js ssr ssg, next js ssr only
Id: pjhjqUrG9O4
Channel Id: undefined
Length: 24min 29sec (1469 seconds)
Published: Fri Oct 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.