The Ultimate NEXT.JS 13 Tutorial (Complete Walkthrough w/ Examples)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
yo what's going on guys welcome back to one of the most exciting videos of the year the next js13 tutorial I'm gonna go ahead and introduce you to all of the brand new features such as the server components inside the brand new app directory how you can share layouts while preserving State and avoiding expensive re-renders and amazing new react features such as streaming and the ability to carry out data fetching inside of our server components it's time to learn next year's 13 wrote the intro [Music] the next js13 is one of the biggest releases of the Year from the cell includes a bunch of new react features including the new server components now it's worth mentioning that at the point that this video is made some of those features being used inside of an xjs13 are in beta however I would recommend that you go ahead play with them give the guys over a visel the feedback that they deserve as it's most likely that these features will remain in react however just be prepared that they could change now in this video I'm going to talk mainly about the app directory how we can change the traditional methods that we used in xjs12 such as get server side props get static props and get static parts and how we can more simply write them using the new next year 13 abilities if you want me to cover more next year's topics such as turbo pack the new nexjs image component new next font component and the middleware updates then let me know in the comments down below without further ado let's jump into today's build so first things first I'm going to use the create next app command to go ahead and initialize my app and I am going to be using the template with tell ncss to go ahead and initialize my Tailwind in a faster manner so in this case I'm going to go ahead and say YouTube next.js 13 Demo you can name it whatever you want now something to bear in mind is that although next year's 13 is a major upgrade to next js12 what the team have done incredibly well is taking on this incremental adoption approach which means that even if you're on next js13 you don't have to make huge changes to your code sure some changes are going to be made in the link component and the image component however your current page structure for how you go ahead and render out your pages doesn't need to change your new pages and the app directory can coexist until you migrate over the code to the newer server components so don't freak out take your time and enjoy the process once this is done we're going to go into our code using YouTube and next.js13 demo I'm going to go ahead and hit code dot to open up my vs code so kicking things off we can see we have a Pages directory and a bunch of other things such as a Tailwind config and everything has been configured for next js12 so looking at this how do we go ahead and convert this app into an app which is using next.js13 well firstly let's just go ahead and run this app to get things up and running so yarn run Dev I'm using yarn as I've got a yarn lock file you can use npm if you are using npm right so if you say package lock yours is going to be an npm so as you can see my app is now running on the right hand side this is the home page in the traditional next 12 format so as you can see our page route is currently in next.js12 are formatted based on of the file name now we're going to go ahead and change this to the new app directory now it's worth mentioning that anything inside of the new app directory is actually going to be a server component now I highly recommend that you have the next js13 upgrade guide next to you as you follow out this tutorial as it's going to have a bunch of tips and tricks that I may not mention inside of this video carrying on we first need to enable the new app directory so we go into our next config head over to our module export and we're going to add in the experimental flag and inside of this object we're going to type in app directory true so once I go ahead and hit save I'm going to have to restart my next server so I'm going to go ahead hit yarn run Dev and you might get a prompt asking for your typescript support so we're going to click allow and you can see that we are now using the new experimental features now what I want you to do is head over to your tailwind and we're going to actually modify our Tailwind configs that way it actually includes the files inside of our app directory as well as our pages and our components folder so in this case this will now go ahead and compile our Tailwind CSS code inside of our app directory as well as everything else that we previously were doing now let's go ahead and create our first ever file now there are seven different reserved keywords when we are going ahead and creating a file we have the layout the page the loading error template head and not found now you can find this information on the upgrade page and you can go ahead and see how is using that reserved keyword to go ahead and build out the file but let's just jump into an example and it'll make a hell of a lot more sense so let's create our first ever page so as you can see now we have a new file directory whereby we have a root for slash segment forward slash Leaf so I'm going to explain what the hell that means so first up on the highest level is our home page in this case we're going to call it page.tsx I'm going to use my handy react Snippets to create a react functional component and here I'm going to go ahead and type in home right now really doesn't matter what you name it here this is going to resemble our home page so I'm going to say I am the home page I'm going to hit save now what we should see if we look inside of our terminal we will actually see that we have a conflicting app and page file found this is because this is pointing to our home page as well as our index.tsx in our traditional nextges approach so we're going to delete our traditional next.js index page and now you can see we automatically got a layout.tsx file created for us so what is a layout file now the new layout component is a really handy way to share different UI components in a kind of hierarchical fashion so the really nice part about this is it preserves the state and it prevents unnecessarily re-rendering several parts of the page so here you can see we have a base HTML with our head and the body simply rendering the children the children is essentially the page.tsx so let's go ahead and see and now you can see I am the home page but you're probably wondering that does not look like we're using telman CSS so as you can see what we previously did inside of our underscore app.tsx file was we imported our globals from our Tailwind CSS now what I can simply do is head over to my layout.tsx and paste it in at the top and we can Simply Save now you can see we have our Tailwind TSS become active so inside of my page I can now go ahead simply pop in a class name make the text red and you should see that we have successfully connected our tail and CSS so what's the benefit of using this new layout approach well I'm going to show you right now by creating a header component so we're going to go ahead and create a header.tsx file I'm going to go ahead and create that file right now so here is an example of a header so let's just assume that this is a random header it's got a padding of five it's got a background blue of 500 and it's going to go ahead and Surround at the top so in now instead of putting it inside the page I can actually put this in the layout because I want it to be available throughout all of my pages on my site now what I can do is I can go ahead and spread the body like so and simply pop inside of here I can use the header component like so this will pull in the header into my layout and this header component will simply be rendered out onto the screen now it's probably better we use our actual correct syntax here so in this case we're going to pop in like so put in a P tag just to say I am a header just for now to be very simple and keep the very basic and as you can see now im a header is going to be persistent across all of our screens from this moment forward but let's go ahead and give it a nice little bit of styling to make it look a little bit cleaner so in this case I am the header so now we have our header component at the top of the page but what if I want to have a second page okay so typically the way it would work in xjs12 is we would have a separate file for example we would have search dot TSX that would resemble the forward slash search page directory well inside of next year's 13 now we have a photo structure now in next year's 13 we follow a new photo structure we have the root segment which is the starting point this is essentially the index of the website then we have the the segment which is going to be the next most important part and then we have the leaf segments and it can be recurring on as you need it to be right so in this case we're going to go ahead and create a nice example using a to-do example so a very basic tutorial that we're going to go ahead and create today now in order to have four slash to Do's I just create a folder called to do's and inside I have all access to all of those seven reserved file names I spoke about previously so let's go ahead and dive into the first one let's type in page.tsx I'm going to use my react functional component snippet and now I can go ahead and call this the to-do's page and as you can see this will actually create a page under forward slash to Do's but it follows this new page layout so as you can see we have this root layout and then we have the segment inside of it if I go to forward slash to Do's what we will now see is the to-do's page being rendered but what's really cool here is the layout is going ahead and being persisted across the different screens so I'm going to go ahead and actually Implement a button inside of the header component which will allow me to go back to the home page so I'm going to use the link component and previously we would have had to have an a tag inside of our link tags however index.js13 now by default it generates an ATAC for us so now I can simply create a link called home which is going to go ahead and go to the home directory I'm going to go ahead and pop in a bit of styling and then remove the IM header button so as you can see now we have a home button now when I'm on the to-do's page if I click this home button you can see it loads up the home page okay so as you can see everything that we've created so far is actually server components not client components so this is something to understand whenever we are in the app directory all of our components are server components by default so next up I want to create a list of the to-do's that can be listed out on the page so what I'm going to do is create a handy little to Do's list component which will render out all of the to-do's on to my page like so so I'm going to actually use our current file directory and what's nice about this directory is we can actually keep our components next to the level at which they're required which allows us to essentially remove the components folder however you can still have a components folder just bear in mind that if it's outside of the app directory it by default will not be a server component so in this case I'm going to go ahead and create a to-do's list.tsx component we're going to create this to-do list and inside of this component I'm going to Simply go ahead and create a call to fetch my to Do's now typically this is something that was unheard of before you wouldn't be able to go ahead and make an await code to fetch some to-do's inside of your functional component typically you would have to have a piece of state and you would you were not allowed to make your functional components async it was just simply against the rules well now now we can do that as this is by default a server component so we're actually going to go ahead and create a fetch to Do's function which will help us go ahead and Achieve what we need to do so I'm going to go ahead and create a fetch to-do's function which is an asynchronous function and inside of this function I'm going to make a call to a API an external API and this is a dummy API called Json placeholder and what this API will do is it will return me an array of to do objects so next up we're going to go ahead and actually pass the information so once we go ahead and get the Json from our response this will give us back the to-do's now I actually know the type that this comes back as so what I'm going to do is create a type definition file so I'm going to go into my code and type the typings.d.ts file and inside of here I'm actually going to create a type definition for my to-do as I'm going to be using it throughout the code now what we can do is we can simply cast this to our to do component once we've done this all we need to do is simply return the to-do's 2 to the appropriate function so as you can see now what we can easily do is we can actually go ahead and fetch at the highest level now in or react and this is thanks to it being a server component and now one thing to bear in mind is if you ever need to use any kind of Click Handler or a hook or any interactive element that requires binding to an element you need to switch to a client component and I'm going to go ahead and show you a nice little graphic of just how to do that in a second but for now what we're actually going to go ahead and do is render out the list of items in a simple mapping like so so right now I'm going to go ahead and wrap our entire return statement in fragments and pop out a map with the link component like so and all this will be doing is it will direct us to to Do's forward slash the to do ID that is returned and it will list out the to-do names so essentially all we're doing is we're listing out a bunch of to-do's onto the screen now inside of our to-do's component I just need to go ahead and render my new to-do's list component and we need to import it like so now one thing that's a known bug at the moment with the typescript and the cell team is that they don't currently have the typescript definition so by the time you're watching this this will most likely be fixed however there is a hacky solution however for now until they have been completed I am simply going to typescript ignore this error and I'm going to get a bunch of hate for that in the comments but it's okay so let's go ahead and go over to forward slash to Do's now on the to-do's page we should be able to see a list of all of the different to-do's that have been popped out from that API call so this is actually being rendered on the server so at this point when we make the fetch call if I make a simple fetch to say this is the to do's and we simply log it on what we should see is now it's only being rendered out in the terminal for the server so something to know here is that as we are only rendering this on the server it's only the console logs will only be visible on the terminal and not on the browser now as we are currently using a link component what it will try to do is it will try to pre-fetch these pages in advance to help it seem like it's an instant user experience so in that case we need to actually go ahead and create these pages so that next.js knows what the hell to do when it sees that route otherwise we're going to get a bunch of Errors where it's trying to find the page but you simply can't find that page so you can see to Do's 31 32 is trying to find it it can't find it so at this point now I need to create a dynamic route now how do we create a dynamic group well typically what we would have done is create a file inside of a folder with the square bracket notation now in this case all we have to do is create a folder inside of our want to do's and we simply give this the to do ID so this could be given the ID it really doesn't matter what the name is you just have to make sure that we relate to that in our code down the line so I'm going to create a to do ID folder and inside of that we're going to use the same syntax that we were previously using page.tsx so I'm going to create my functional component and I'm going to call this my to do page and this is going to resemble the page for the to do now to go ahead and access the individual to do ID so in this case if I went to forward slash number three I need to know what the root query param is so I need to know what number is at the end or what the dynamic root value is so in this case we actually get a bunch of props that come back now you can Contour log these out and you'll find that you get a bunch of params and search params but in this case as we don't have the type definitions available yet I'm going to go ahead and create my own page props like so so I'm actually going to create my page props and then I'm going to go ahead and call that the params so I've already done this work for you so we've got the params and then we've got the to do ID now the to-do ID should correlate to whatever you've given the value over here so at this point we've got our props I'm going to destructure the params and then I'm going to go ahead and get out the to do ID like so okay so now I've got my to-do page and all I can do to Simply go ahead and pop things out is I can go ahead and say to do ID now if I'm on to Do's forward slash nine we can see that it goes ahead and says to do page number nine now what we're going to do is we're going to Leverage The Power of the server components to actually go ahead and fetch each to do as we get onto this page so let's go ahead and do that right now so I'm going to go ahead and say const to do equals a weight and in order to use a weight we have to make our overall function asynchronous and then I want you to go ahead and create a function called Fetch to do we're simply going to pass in the to-do ID to this function so I'm going to go ahead and create the outline of the function like so secondly I'm going to go ahead and make an async awake call to a third-party URL so in this case we've got a API request being made to the Json place order typeycode.com and then we're using our to-do ID that we pass in as query param this will go ahead and load that individual to do from that dummy URL and then we're going to go ahead and pass the response now the type of response that comes back will be in that same to do type that we went ahead and typed out earlier I'm actually going to go ahead and return a bunch of information so we've got a simple P tag with the to do ID the to-do title we have a ternary operator if it's completed it will say yes or no and then we've got the user with some basic styling around it so I'm going to go ahead and hit save and as you can see now it loads up that individual to do based on whichever one is loaded on the screen so as I change it we're on to do number three and so forth and if it's completed it'll say no and just like that it works so what we can actually do now is this is actually essentially doing the same job as a server side rendering so if we were to actually go ahead and build this right now if we did yawn or run build what you will actually see is that this page will be known as a server side rendered page and that's because what we are essentially doing every single time is a fresh vegetable to go ahead and get this working so as you can see the to-do's page is known as a server-side rendered page so I'm going to show you how we can Implement all of the clever rendering techniques such as static site generation server side rendering and ISR using the following so now what they've done amazingly is they've upgraded the fetch API so all we need to do is add a second argument here and we type in cash now on Cache we've got a bunch of different options so very simply if we wanted to force the server-side rendering method that we previously knew we simply put in no cache if we want to go ahead and enforce a static site generation approach then we add a cache and if we want to go ahead and have ISR whereby we can revalidate the pages after a certain given time time then we need to go ahead and have in the following like so we add in next and then we pass in the revalidate argument with a time so this is the number of seconds that we want to allow to pass before next year's we'll try to revalidate that page in the cache which is incredibly powerful if you don't know how to do so already so I'm not going to dive too far down ISR but that's essentially how we go ahead and get this working now you cannot use SSG so static site generation so where we have the ability to Cache or the next ISR if you aren't telling next shares how to figure out the initial pages to go ahead and render so how does it know whether to render to Do's forward slash one up until 100 it has no idea at this point how to go ahead and do that so what I'm going to do is I'm going to keep this here so we have ISR up to 60 seconds revalidating our cache and then I'm going to use the new generate static params function so in the this argument what I'm going to do is I'm going to create a function and this function is basically going to allow us this is a reserved function similar to get static Parts in the previous next.js12 and what we're essentially doing here is we need to go ahead and make a call to our backends we're making the same core that we had previously to our to do this so where we are able to fetch the to-do's we're actually going to use this exact same argument so what you could do at this point is refactor this code and pull this out as necessary however in this case I'm just going to go ahead and for demonstrational purposes pop this in like so so at this point we are fetching all of the possible to Do's that we can go ahead and render then what we need to do is simply return it in a format which looks something like this so we need to go ahead and actually create all of the page Roots so in this case our arguments would look something like this it would have to do ID one and then in the second argument which would have to do id2 and so forth right all the way up until the final to do in our response so in this case it will go up to I believe 200 responses so how do we go ahead and transform our to-do's into this well it's actually quite simple all we need to do is return the following we're going to go ahead and map through and for each to do turn an object where the key is the to do ID and the to do ID convert the digital ID to a string value now this is probably the biggest thing that I find students slip up on this has to be a string otherwise you'll get an error whereby saying a expected a string and instead you've given it a number so make sure you do that and now we've done is we've generated all of these to do's and we've got back this approach so what we've essentially done now is we've towed next.js how to go ahead head over to this URL like so and generate all of the pages up until 200 okay so now that we've done that what we're actually going to do before we run our build is we're actually going to go ahead and trim this down because we are using a test API I don't actually want to get rate limited uh as I think there's a limit of 50 requests consecutively before they stop your build before they stop your network request coming in so for this demo is I've simply gone ahead and basically spliced the first 10 pages so essentially all we're doing here is we're pre-rendering only up to the first 10 pages right so this is only for the demo purposes however in production you could just remove this line and do that as you need to but in this case we can actually go ahead and test it and you guys can test it very easily like so so I want to go ahead and build this now so yarn run build and now what we should see is rather than it being a server-side rendered route it's going to actually statically generate each of those pages so let's have a look so now you can see we've got this dark tick which is static site generated and this is saying that it's generated the pages for to-do's forward slash to do one two three all the way up until the 10th page so now if we were to go ahead and actually run our pre-built website so in this case let's do yarn Run start this will run our code not in developer mode but instead using the build output so this one yarn Run start and what we should see is it's incredibly fast for everything up until the 10th to do so let's go ahead and check this out so if I go to forward slash to Do's what we should see is all of our different to-do's and if I click on number seven you see how quick that was super fast at loading right if I go to number two it's super quick if I go to number six it's super fast now remember I said it only built up to number 10. so to do is four slash ten so what happens if I know for a fact that there is about 200 to Do's on that list previously what we could do was something called fallback we had a fullback option in ISR and what this did was if the original page wasn't statically generated at build time what we could do is we can attempt to server-side render that page and actually cache it if we get a hit back and if we don't get hit back we can actually say whoa whoa there was no page that was returned so let's give this a try now by default this behavior is actually on so if I went ahead and aimed to go to for example 15 which was not statically generated I can go ahead and see that it actually loaded for me and it would have cached it if I go to 100 you can see that it took a little bit longer because it had to server side render that page and then go ahead and cache it so now if I go back to 15 it's extremely fast if I go back to 100 it's extremely fast but if I go to 101 server side renders it caches it and we now have the ability to dynamically server side render the pages which were not statically generated at build time this is really powerful and something to absolutely know about this is that when we generate those pages they are not updated so they are still statically generated Pages which will stay that way the only way to revalidate those pages and ensure that they're up to date using isops or incremental static regeneration is by having the revalidate option so this means at most at every single 60 seconds when a user tries to come to the page after 60 seconds has elapsed it will basically invalidate the cache and it will rebuild now it's important to know that the user who comes there before 60 seconds is going to get served the old version and after that 60 seconds it will server side render the new version of the page and it will replace the cache and then so forth so you will always be within the correct version of that page within 60 seconds in this example and you can change that number based on your requirement now we can actually toggle the ability to generate or so other side render pages that were not originally created when we statically built the website by doing the following so we can use this Dynamic params equals true option Now by default this is true and this is a keyword that we can explain it tells next.js that we actually want to have that ability to try to server side render a page the problem with this is that if we do this and we try to access for example the one millionth to do what we'll find is we get this unexpected Behavior where there was no hit and nextges didn't know what to do so in order to avoid this problem what we're actually going to do is firstly I'm going to restart my app in development mode so that way I can actually go ahead and get a real time server-side rendering approach each time and I need to basically put a simple check in at this point so what we actually have access to now is a handy new function called not found that we can import from next navigation so at this point what I can do is I can simply go and say if there is no to do dot ID so if there is no to-do ID I simply want to return the not found argument okay now if we hit save and I go to the 1 millionth page and I hit enter what it will try to do is it will try to server-side render it it will then get a to-do response back which would probably be undefined in this case it found that there was no property and then it would return a not found page and then the next natural thing is well that's pretty cool but this 404 does not look the nicest right again they've got us sorted over here with the new seven reserved pages that we can use one of those pages is The not found TSX page and you can use the dot JS file notation as well I'm just showing you the typescript way so in this case I'm going to go ahead and create a functional component here to resemble our not found page and this is going to say whoops we couldn't find the to do you are looking for right so very simple quick little explanation hit a refresh and now what we will find is you'll simply get this message on the screen if you ever hit the 404 State however if I hit something that was present in this day so for example 55 this wasn't present in the initial build but it was server side rendered in there you can see 55 now it's worth mentioning when you're running in developer mode so yarn run Dev or npm run Dev it's always going to server side render the only way you can really test your statically generated pages is by doing yarn run build or npm run build and then npm run start to go ahead and see the effect of your statically generated site that way you'll notice that immediate speed boost for the pages which were initially loaded in now we're going to actually customize it a little bit further so on the to-do's level so at this level I'm going to create a layout dot TSX file and on this file I'm going to go ahead and put the following code so I'm going to go ahead and simply use use a to-do's list cool so in this case I've got my root layout at this level and what you are doing here is we're returning the main in which case it's going to be a flex box and we have two children of that flexbox one being the to-do's list and one being the rest of the children which should take up the remainder of the space so I'm going to Simply hit save so now what I need to do is head over to my initial page and we can actually simplify this we can simply go ahead and put a H1 thing this is where the to Do's will be listed dot dot right and what's really nice about this now is as you can see when we reach this page forgive the UI we haven't put much effort in but in this case we've got all of our to-do's here and when I select one of my to Do's as it's taken this incremental layout approach as you can see we've still got our header from our root layout and then we're inheriting our next segment layout now what you can see is it will only re-render this portion so as you can see when I click on one of these to Do's what you'll notice is only this portion of the screen is going to get re-rendered so let's give that a try and see if it works so I'm going to go ahead and click on this for example to do number two and as I click that you see it loads in my to-do number two if I click on number five it will go ahead and load up number five and so forth right so this works in the exact same way but now our code is incredibly simple so as you can see all our code consists of is the presentational logic for what should be on that page it is separated from the initial layout so all this is going to take is a mindset shift to understand how we can separate our different components from one another but the power and the trade-off is incredibly awesome next up we're going to use an example of a search and in this example I'm going to demonstrate to you a few different aspects how we can use the new loading file how we can use the new error file and how we can go ahead head and allow for streaming inside of our components so that way when our server components are loading we actually get a nice loading indicator to allow the user to have a immediate response on the page we're also going to go ahead and show you how to create your first client component if you need to have some interactivity and let me know what's been your favorite so far down in the comments so what we're going to do right now is we're going to go ahead and go to our top level so I'm going to click on app now I'm going to create a new route for something called a search okay now on the forward slash search room I want to go ahead and create a page.tsx which resembles my search homepage so in this case I'm just going to call this one as such now as you can see just like that if I go to my forward slash search page automatically have my header completed which is in this case has automatically been inherited down from the layout for me so now what I want to do is I want to create a layout component for this segment okay now for this segment I'm going to go ahead and pop the following in so what I ideally want to have a search so in this case you can see we've got a main we've got our div and then we've got a div here so in this case I've got a flexbox with some space between them we've got two children components and one is a search component that we are going to go ahead and create now the second one is the rest of the page that will get loaded out of this root we need to create a search component so let's go ahead and do that right now so we're going to go ahead and create a search dot TSX component right and let's go ahead and pop in our search components so say I am a search component so very simply just like that we now have a search component let's go ahead and hit refresh and as you can see now on my screen I've got a nice easy simple layout based on the following but first div which is just a simple title to say search then we've got a gap and we've got our second div and the top part is going to be the search component responsible for allowing the user to type in so this is going to be a client component and then we're going to have a button to search and it will take us to a search forward slash the search term root and that's going to dynamically server-side render the results on the page so let's jump into how we can achieve this so first things first let's create a interactive assert a client-side component now the reason we're going to need a client-side component right now is because of the following now our thought process when we're using next.js13 is this we should always trying to think of the solution in regards to a server component because we're going to essentially be getting the benefits of a server component we're going to lose the risk of exposing keys we're going to allow the heavy lifting to be done off of the client's device which should speed up a lot of the interactivity and what we should only do if we require it and only if we need to we convert it to a client component so in this case I need an input so that the user can type in a search term so I have to use a client component now you can head over to the when to use a serverless client component section in the next JS beta docs and you should see this right here and as you can see the main reasons for using a client component is when you need to add interactivity or event listeners or you need to use State and lifecycle effects browser only apis or custom hooks or class components so think of it anything that requires statefulness or anything that requires a browser or any element to be binded to come be done on the server has to be done on the browser so at that point we convert to a client-side component so it's very easy to go ahead and convert to a client-side component let's head over into our search components and to do this all we need to do is type in the following directive at the top we type in use client and just like that we now have a client-side component first things first we're going to go ahead and create our search field so we're going to first import some dependencies that we might need so we're going to import the use router from the new next navigation not next router then we're going to import the form State U State and react from reactors we're going to need those eventually then we're going to write the body of our function and Export it accordingly so this is a normal client-side component we're then going to prepare some states so in this case we've got our search that we're going to go ahead and eventually use for the input field and we're going to get a router instance that way we can make redirect once the user actually goes ahead and inputs a search term then we're going to go ahead and create our hopeful handle search function which will be bound to a form that will be submitted at this point so let me explain what's going on here so first things for first let's hit save and let's see the output that we can see on the page so I'm going to give our button a little bit of basic styling so that way it can go ahead and look a little bit more like a search button and in this instance what we're essentially doing is every time the user types in we are simply mapping our on change to the piece of State inside of our react component so in this case we can have we have access to our search term at all times now what we want to do is when the user actually submits the form so on submit it will actually go ahead and submit this handle search function and we're going ahead and using the correct type definitions now if you don't know the type definitions here's a little trick how you can go ahead and get them so if you ever need to get the type definition but you have no idea and you run into this error simply go ahead and use the following trick I love sharing it with everyone simply put an e and an arrow and you will get the actual type definition over here so form element HTML form form element you simply you pop that in just like so and then you replace the core like that and that's how you get the perfect element type every single time so in this case we're going to prevent default behavior of refreshing we're going to set the search to empty after they search and we're simply going to push the user to search forward slash the search term we want to redirect the user so if I type in JavaScript we are going to redirect the user to search forward slash JavaScript so the segment will be search the leaf node will be JavaScript at this point we now need to create our new search term page okay so at this point it's very simple to do that all we need to do is create a folder and call it search term so in this case we're going to say search term and inside of here we're going to create a page dot TSX and this is going to resemble our search results page okay now on this on this page it's going to be a very simple layout so on this page we're actually going to go ahead and do the following so firstly we need to go ahead and grab whatever the user has typed in the search and actually use that to make a fetch call to an external API which will give us a bunch of search results so what we're actually going to do here is we're going to go ahead and say const search results equals a weight search search term okay now the search term we get from our params so in this case we're going to get a bunch of props so let's go ahead and get our props from our page props and I've written out our prop types that come through here this is very similar to what we did earlier so as you can see we get the props coming in the form of our page props like so we're going to destructure this to get the search term out of it nice we're going to make a function asynchronous and then we simply need to go ahead and create a search function so in this case I'm going to create a search function which is an asynchronous function it takes our search term as an argument now at this point I've made a call to an external API so what I've actually done here is make a call to the sirpuppy.com forward slash search API and this is a really nice API that you can use to go ahead and create essentially a Google Search now all you need to do is sign up to their site so it's free to do so and they give you a really nice kind of uh I think it's 100 free searches when you sign up so let's go ahead and test that right now so all you need to do is head over to your dashboard create a free account and you'll get a nice private key that will be shown down here you simply want to copy your private key and don't worry about copying my key because I'm going to invalidate it after this is done and then you want to go ahead and store it in your environment variables so in this case I'm going to go ahead and create a environment file so end local I'm going to go ahead and pop in my API key like so paste it in and I'm going to close my file so in this case we've got a sub puppy search the search term is going to be our query param and then we're passing in the key like so now they do have a node.js library however we're not going to use it to keep things very simple in today's build I'm also going to go ahead and write the bare minimum type definitions for the response that comes back so what I've actually saved you the headache of doing is I've condensed on the search results that come back in the form of the array over here like so so the actual search results are something along the lines of this so we actually get a massive object back with lots of different keys and values but in this case all we care about is the organic results section and a few different fields so what we're actually going to do at this point render out some results on the page I'm going to pop in a P tag where we go ahead and we say we search for the term that is going to be whatever the user search for we've given it a bit of minimal styling then I've got a ordered list and we're simply mapping through the organic results and we're listing them out accordingly so let's see the output of this on our screen right now as you can see we've actually got a really nice web page on the screen so if I was to go ahead and show you right now how this works let's go to our forward slash search react.js and let's click search and as you can see we have a slight delay and then it loads onto the screen now the reason why we get that delay is because it's actually blocking at this point but what is incredibly powerful is that with next year's 13 we have the addition of these new loading and error files so in this case if I create a new loading.tsx file which is a reserved file and we create a functional component so in this case I'm going to go ahead and call it loading now I can say loading search results and what would happen is at this level when we have any blocking function it's going to go ahead and show that loading placeholder as a fallback so let's go ahead and give that a nice try so let's actually head back over to our search term and let's go ahead and type in something like Papa react and hit search now you can see loading search results and then bam you can see the course comes up amazing stuff look at that there you go so as you can see that's really awesome and it works through and through so what we actually have right here is a server component with only one slight small part of it being a client-side component so this entire site so far has been achievable with server components and the ability to stream in the data as and when it is ready so in this case if I was to type in JavaScript and hit enter so Java Script oops it would help if I spell hit enter now you can see loading search results and Bam it's jumped in so that is actually the power of streaming inside of react and xjs handles it beautifully now what happens if we have an error so let's go ahead and assume that we had an error at some point and I'm going to go ahead and simply throw an error saying whoops something broke okay now at this point I don't want my entire code to break and freak out instead all I need to do is create a error.tsx file okay now in this error.tsx file on the next JS website you can actually find a really nice error example so if we head over to the error page right here you can use this as your boilerplate to go ahead and get this set up now this is a client-side component because the arrow is likely to happen on the client so in this case we're going to go ahead and pop this in and as you can see it gives us two arguments the error and the reset function the error is essentially going ahead and being collected on a user effect so when the component mounts if there was an error it's going to log out to the user's browser and then we're going to go ahead and say something went wrong now something to bear in mind is if we were to go ahead and do this now so if I was to go ahead and hit save what we will see is it will throw an error now on the developer environment we will see this error being shown on the screen but on production this won't be shown to us and as you can see instead what will happen is we will render out the UI for or the error so in this case you render this out so you can have something quite nice you know a picture of a dog confused saying whoops something went wrong whatever you really want and then you actually have a ability to reset and in that case it resets the error boundary so we can handle our loading States we can handle our error States and we can do so much more with next.js 13. now if that wasn't enough if you want to go ahead and customize the head attributes so for example in this instance if we were to go ahead and close this out as you can see I've got this horrible head syntax right here so what I want to instead do is on my default page layer I'm going to enforce that you know my majority of my website says that this is Sunny's website okay so this is going to be throughout the majority of my website so if we refresh now you can see the title with Sunny's website but I want it to change based on if I'm in the search section or if I'm in the to-do section of my site so let's go ahead and demo how I can do that as I mentioned there was a bunch of different uh reserved file names and I had in a head.tsx file now in here I can actually go ahead and create a simple functional component call it head and simply all I need to do right here is start putting in the properties that I would like to go ahead and inject into my head document so at this point all I have to do is go ahead and type in the title so in this case I can put in the title and I can go ahead and say the search page right so this is going to be the search page and hit save right and just like that now when I come onto this page you can see it enters in the search page like so we have no errors on the screen and that's where it can go ahead and work perfectly right if we went ahead and went to the to-do's section you can see it goes back to Sunny's website right even if I'm on to do number five or wherever I am on the page right now so if I go ahead and click into my to-do you can see that I'm still on Sunny's website because the fullback was the title Sonny's website so it follows that hierarchical approach approach and it only activates or changes our head component if it finds one at that segment or Leaf node now we are not finished yet I told you this was going to be a full in-depth tutorial and I meant this we actually have another amazing feature that the guys over at versaille have actually introduced that not many people have actually spoken about and this is the introduction of group Roots so when our photo structure gets a little bit more complicated let's imagine we had one more route okay so now I have a forward slash developer page and we have a forward slash search search term page and a forward slash to do this page but let's imagine that the search and the to-do's was purely for users and we only wanted a page for the admins but we wanted to separate it in regards to IR folder structure now in order to do this you would wonder that if I introduce a new folder I'm actually going to break my routing system so what the guys over at nxts did is that introduced us to the concept of root groups so now we have this amazing way to go ahead and do this by using parentheses so as you can see we can separate our concerns inside of our app and it will be emitted from the page root so if we have a marketing section it would not show marketing about as long as we have these parentheses so let's go ahead and give this a try in our code and this shouldn't change any of your routes so if I go to the app level and I create a folder and I'm going to call any of my user-facing stuff user I'm going to put this inside the user's folder and I'm going to create another folder at this level and we're going to call this the admin stuff now this does not protect your roots they will be introducing a feature to help do that very shortly however that's this does not actually change or affect any of the routes as such All We Now can do is we can actually move each of these into the appropriate folder so the search is going to be something for the users and we're going to want to update all of our user Imports and so so forth for the to-do's yep there we go and as you see update Imports yes we want to do that and then we want to go ahead and pop in our developer into admin as well so once we make that change make sure you've updated all your Imports correctly and then you want to go ahead and simply restart your server as you made pretty drastic photo change okay so once we've done that hit a refresh and what you should see is none of our routes have been affected by this change if I go to my forward slash homepage we see that it's the home page if I go to my search page we can now see I still get the search page my search still works so if I click on react we still get the same search results that we expected previously and if I go to my to-do's page I still get the to-do's that I previously built out before you can see that no change has been made to my folder structure so this is something that I haven't seen many tutorials about but I think it's actually a really cool addition to the next js13 Arsenal of tools that have been delivered to us now it's worth mentioning that if you do this change we have to consider a certain few things if we want to have a layout inside of either the users or admin what we have to do is remove it from this top level because essentially these folders are invisible to some degree which means that if they're invisible we can't actually where we if we added a layout here it would also resemble the same level as here and if I added a layout here it would also resemble the same layout as here same for the page and so forth so at this point if you want to have a home page you can keep your home page here or you can keep the layout at the top level but if you want to have a separate page in here or in here you can only have one home page right so in this case this can be a little bit confusing because we have only got one folder so let's imagine I had another folder in here called dashboard so let's just imagine it was a dashboard forward slash and then that had a file inside of it so page.tsx rfce very quick boilerplate code for that let's just call that dashboard so in this case now if I had my app which has two things inside my admin which has two things inside my users which have two things inside and I moved my page for example to this level now that would be completely fine but if I added a page here and I added a page here they would be fighting for the forward slash directory because they're both essentially at the higher level so if we do want to have separate layouts for each one we would have to delete the layout at this level and create two new layouts here but we can only have the page at one of these levels right now as I mentioned this is completely new so I if I have made any mistakes or if anything doesn't make sense like it should then please feel free to comment down below I'm happy to take on feedback as always I'm learning this Tech as well I just want to bring more value to you guys as well now finally as a bonus I want to show you the react suspense boundary so the react suspense boundary is an incredibly awesome but often misunderstood component so I want to show you nice little demo of how we can use this and how it's actually really powerful if we think about it so on the home page I'm going to have two simple calls so I'm just pretending at this point all I'm trying to show is how we can wait on two different promises in a different way so at this point I'm going to have two divs and pretend that this was a shopping trolley or some other aspect right so I'm going to show you how we're going to like effectively show you this in a second right for now until a typescript fix is around we're just going to ignore at this point what I'm going to do now is I'm going to wrap my suspense I'm going to wrap this with something called the suspense boundaries so I'm going to wrap the first one with a suspense boundary and I'm going to wrap the second with a suspense boundary like so okay so this is where it gets really cool now just like we have server components that get blocked by their await course for example in the search search term page when we are fetching our search term all right so when we're actually fetching our search results we were showing a loading state right so at this point we can also do this using a different component so if we were to use the suspense boundary we can actually use something called the fallback component and here all it takes is a little component inside of it so at this point I can simply put in a P tag that says loading the to do's and let's do the exact same thing at this point by saying loading the shopping trolley and to emphasize this what I'm actually going to do is you're probably wondering they're going to load at the exact same time so for the to-do list when I have my fetch to Do's I'm simply going to add in a small little timeout which is going to resemble a random timer from one to five seconds okay so that way they should go ahead and pop in at different times so all I'm doing here is I'm waiting a random amount of time between one and five seconds every time fetch to Do's is called so at this point now what I can do if I go back into my page.tsx so let's have a look what happens now if I go home if I hit the refresh button you can see we've got loading to do's and then we've got loading the shopping trolley which takes a different amount of time so before I run this test I'm actually going to go ahead and have a P tag styling over here hit save and now if I was to go ahead and refresh you can see that the top one BA and then the second one came in second and as you can see here they will pop in when they're both ready accordingly now this is the power of streaming it won't block our UI instead it will just stream in the data as and when it is available this is incredibly powerful and it's the power of the suspense API and as you can see this was also happening inside of the search page previously so when we were previously searching for a different term so in this case if I typed in something like Papa react and we hit search instead now with essentially Weighing on that promise and then when it's ready it will stream in the data as it's ready so what's really awesome about this is using the new layout we're no longer unnecessarily re-rendering components such as this or such as the search field down below right instead now we're only re-rendering the area where the new data was added in so as you can see next year's 13 requires a little bit more than just a play with new tech approach it requires a little bit of a mindset shift to server-based thinking first so now we think of things in terms of server components and then we only use client components as and when we need them it will take some time for all of us to get to the point where we're pros at this but I promise you on this channel I'm going to be delivering so much content which leverages this so you will have plenty opportunities to go ahead and run with this and before you know it you'll be a pro at using next year as 13 and transforming code from next year's 12 to next year's 13th with that said I hope you've enjoyed this video I have actually already been on the grind and covered tons of next year's 13 content in my course zero to full stack hero if you're interested head to papareact.com forward slash course as always guys if you enjoyed this content please make sure to like And subscribe let me know right now in the comments down below what part of next js13 is your favorite until next time it's your boy Papa red nobody love you [Music]
Info
Channel: Sonny Sangha
Views: 236,127
Rating: undefined out of 5
Keywords: react, developer, reactjs, html, css, js, javascript, papa, papareact, papa-react, tutorial, frontend, webdev, dev, clone, backend, fullstack, motivation, reactnative, react-native, redux, typescript
Id: 6aP9nyTcd44
Channel Id: undefined
Length: 56min 55sec (3415 seconds)
Published: Sat Nov 05 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.