Next.js Tutorial - 38 - Pre rendering + Client side Data Fetching

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back everyone now for the last bit of discussion around client-side data fetching i want to show you how to combine it with free rendering for our example we're going to look at building an event listing page basically a page that shows a list of events happening around you since we want seo and the list of events be fetched at request time we're going to use server side rendering with get server side props function once events have been loaded we're going to use client-side data fetching to filter the events now ideally both pagination and filtering would take place client-side but for this example we're only going to focus on filtering back in vs code we are again going to make use of json server for some mock data in db.json i've created an entry called events which is an array with 10 objects each event has an id title description category and date for our example we're going to fetch this list of 10 events and then client-side we're going to filter only the events with a category of sports not the most practical data to work with but it will serve the purpose in the pages folder i'm going to create a new file called events.js within this page our first task is to fetch the data required for server side rendering since this is a topic we've already covered i'm going to go over it fairly quick export async function get server side props and within the function const response is equal to await fetch and the url is localhost 4000 slash events once we have the response convert it to json so const data is equal to await response dot json then we're going to return an object which contains props which is again an object and we have one property event list which we are going to set to data now that we have the necessary data we can define the component to render the list of events so function event list and from the props we destructure event list for the jsx we are going to return and h1 tag that says list of events and then we are going to map over the event list say event list dot map and for each event we're going to return a div tag whose key prop is equal to event dot id and within the div tag an h2 tag that renders event.id event.title event.date and finally the category below the h2 tag in a paragraph tag we're also going to render event dot description finally an hr tag once the component is defined make sure to default export it export default event list if we now start our json server so yarn serve hyphen json and also our nexus app yarndev and navigate to localhost 3000 slash events we should see the list of 10 events being displayed inspect the network tab and the html is in fact pre-rendered so nothing new here are server side rendering with get server side props but after we have rendered the list we want to allow the user to filter the events based on the category now ideally we would have a side nav with a list of all categories that the user can select to filter the events but to keep this simple i'm going to add one button that will filter events with sports category the aim here is to help you understand combining pre-rendering with client-side data fetching and not topics that are more react-specific i'm pretty sure you know how to render a list of categories and handle the click of a button so back in vs code in the event list component jsx above the heading i'm going to add a button the text is sports events and on click of this button we are going to call a function called fetch sports events let's define this click handler const fetch sports events and this is an async function within the function we fetch the filtered list of events i'm going to copy paste the two lines of code from get server side props but in the url we can now add some json server magic we specify category is equal to sports as a filter now that we have the filter data we need to render it however for that we need to store the data in a state variable and re-render the component so at the top import use state from react in the component create a new state variable events the setup function is set events and the initial value is the event list from get server side props this of course is the prop we have passed in inside fetch sports events we now call the setup function updating the list of events to be rendered so set events and data in the jsx we use events instead of event list we now go back to the browser refresh we have a list of 10 events if i click on sports events we now see only four events with category is equal to sports and this as you can see happens client-side so we have pre-fetched 10 events for seo purpose but then the filtered data fetching takes place client-side on click of a button but at the moment if i want to share this list of filtered events with a friend or if i want to bookmark this filtered list of events it is not possible the url is the same for filtered list as well as the entire list of events we can however improve this by making use of shallow routing with shallow routing you can update the url in the browser without running the code inside get server side props for that we need to make a couple of changes so back in vs code first in get server side props we need to check if the category query parameter is present so specify the context parameter and extract the query object from the query object extract the category parameter then build the query string so const query string is equal to is category present in the url if it is category is equal to sports if not it's an empty string hard coding sports is in fact intentional once we have the query string append it to the url so localhost 4000 events question mark dollar curly braces query string finally in the fetch sports events handler we need to push the category filter to the browser url so import use router from next slash router and call it within the component const router is equal to use router then within the function router dot push and we push slash events with category is equal to sports the second argument is going to be undefined as it is not necessary and the last argument an object where we set shallow to true let's now save the file and test it out on page load of slash events we have the list of 10 events pre-rendered if i now click on the sports events button we filter the events client side but the url is now updated as you can see and because of this if we now refresh and inspect the document that is downloaded we see only the list of four filtered sports events this means i can now share this url with anyone and they would see the list i am seeing it also helps with seo what is happening is when we reload the page get server side props is run and now it sees the category query parameter is present if it is present the url fetches the filtered events and passes it into the component as data and this data is used in our state variable which is used to render the list of events as you can see it is pretty easy to combine pre-rendering with client-side data fetching also this example uses get server side props function but the idea remains the same for get static props as well now at this point i know you might have a few questions in mind let me try and answer those questions your first question might be about the filtering function itself hey vishwas you have fetched all the events in get server side props so in your fetch sports events function why don't you simply make use of array.filter to filter the events client side now that is a good question to have but array.filter would only work if we are assuming our entire list of events is fetched at once i have fetched all 10 events because it is a very small number in a real-world application you might have 1000 or 10 000 events in such a scenario you would be fetching the first 100 events on the initial load when you have fetched only the first 100 events if you were to use array.filter you would be filtering events out of those 100 events and not the entire 10 000 events in your database you would probably have api pagination and filtering in which case you would need to make api requests every time to fetch the filtered list of events that is the reason i decided to make an api call in the fetch sports events function the second question you might have is probably the more important one here hey vishwas why are you using query parameters to add filters instead of making use of dynamic pages where the dynamic segment can be a category you could then make use of context dot params and regular routing to achieve the same result right let me tell you this is an excellent question to have thought about the answer is yes you could do that you can create an events folder with index.js as the root page and then a catch-all route to handle filters as part of the url itself so if a user would apply let's say two filters the url could be slash events slash filter 1 slash filter 2. you can extract both these filters and pre-render the data however this becomes a problem when you have a lot more filters to work with consider a site like amazon where you have a side nav with 10 to 20 filters for a product in such a scenario extracting the filters and mapping the value to the filter type is very very difficult and probably not even feasible imagine a url like slash product slash filter one slash filter two slash filter three slash filter four till slash f10 keeping track that f1 is for brand f2 is for price f3 is for color and so on just becomes very difficult to manage the easier way to do all that is to use shallow routing with client-side filtering now if this was a bit difficult to wrap your head around at the moment please don't worry about it once you start working on real projects you will soon figure out what is feasible and what is not when you do that you can revisit this video to understand better the concept of pre-rendering combined with client-side data fetching and shallow routing alright that is pretty much what i wanted to cover in this video thank you all for watching please do leave a like if you're enjoying the series and i'll see you in the next one
Info
Channel: Codevolution
Views: 43,295
Rating: undefined out of 5
Keywords: Codevolution, Next, Next.js, Next JS, Codevolution Next.js, Codevolution Next JS, Next.js Tutorial, Next.js Tutorial for Beginners, Next JS Tutorial, Next JS Tutorial for Beginners, Next Tutorial, Next Tutorial for Beginners, Next.js 11, Pre rendering + Client side Data Fetching, Pre rendering + Client side Data Fetching in Next.js, Next.js Tutorial on Pre rendering + Client side Data Fetching
Id: yFvLLPBubfw
Channel Id: undefined
Length: 15min 55sec (955 seconds)
Published: Thu Jul 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.