Implementing Infinite Scrolling With React

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi in this video we're going to implement an infinite scrolling in react and if you don't know what an infinite scrolling is well you can see an example here on the screen let me open up the developer tools and set the network speed to slow 3g or fast 3d just to make sure to see this loading and you can see here that as we scroll down more and more contents will be automatically fetched for us and this is what an infinite scrolling is you can see it right now and all over the internet especially in social media applications for example on instagram if you go to the home page you can just scroll on and on and on and as you scroll down more and more content will be fetched for you and you won't you may not even notice that so this is what we're gonna do in this video we're gonna go ahead and implement this application so let's just get to it what you need to do first is to go ahead and grab the story code from github and by the way we've been working on this project in the last video i published on this channel if you want go ahead and give it a watch link is in the description box below and that way we're going to go ahead and talk in great details how to build a pagination system and node.js so yeah if you want to go ahead and give that a watch i'm not going to do any code walkthrough in this video so if you want any code walk through go ahead and watch that video and if you don't want to watch that that's fine too i mean just start to read the source code yourself and you know try to figure things out on your own start by reading the readme file and then running the app and yeah just trying to figure out how things work so i'm gonna go ahead and clone this repository so i'm gonna copy this remote over here and if you're not familiar with kits go ahead and download the zip file once i have copied this remote url i'm going to go ahead and open up my terminal and i'm going to navigate to my documents folder and right here i'm gonna run gets clone and that's url and yeah that's it let's just hit enter once done i'm going to open the project file my code to visual studio code i'm first going to navigate to that folder and code all okay now that we have the project files cloned and opened up in our code editor i'm going to go ahead and run the application for that what we need to do first is to install the dependencies so i'm going to run npm install install well we first have to run it in the server directory and we also have two runs in the client js folder to install the dependencies for our react server so i'm going to duplicate this tab and i'm going to navigate to the client js folder and right here i'm going to run npm stall okay now i want to wait a while and let these tasks to finish okay now that the dependencies have been installed i'm gonna go ahead and run the application but before we do that we first need to feed some seed data to our database just to have some data to be able to work with so for that what we need to do is from the root directory of the project files we need to run npm run seed then it will grab some data from the internet and then it will ask us what database we want to use you can choose none if you wanted to but i have mongodb already running in my background so i'm going to choose mongodb and for this question i'm just going to specify yes and now a hunt records been saved to this collection okay and to run the server we need to run npm start and we also need to start the react servers and from the client js folder i'm gonna run npm start also just a quick note to if you want to choose my scale or mongodb make sure that you come to the server folder and then config the dev.js file and right here make sure to specify the right url for either mongodb or mysql these are the default database urls so if you have changed for example the port or whatever else just make sure to modify the string anyway so as i said i have mongodb running so i'm going to choose mongodb and now the server has been started but we need we don't need to go to this url we have to go to the react server url and which is this one local host 3000 so i'm going to copy this url and then open it in my browser okay okay so here we can see the app right now and as of now we're getting back i guess 12 records 12 articles and our job is to implement an infinite scroll link meaning that whenever we reach the bottom of the page we need to send another request to the server and grab the next series of articles and then render those articles on the screen so let's get to it right now so i'm gonna head over to my code editor and before we get started i just wanted to quickly point out at two things as i said i'm not gonna do any code walk through in this video if you want to go ahead and watch the last video i published on this channel but just in case i want to say two things one is in the server folder and then routes and then article routes and this is why we only have one route slash api articles and whenever we send a get request to this we're going to get back some number of articles in this case only 12. and yeah that's pretty much it and we also need to specify one more thing and that is a page number and depending upon what page number we specify we're going to get different sets of articles for example if we specify the page to be one we're going to get back the first 12 articles in our database if we specify the page to b2 we're going to get back the next 12 articles in our database make sense right so yeah this is pretty much all you need to know about the server and then we have this file on the client.js folder which is written in react and then in source and then components and then articles.js file so here's our articles components it's a class based component and what it does is that's here in the component it mounts it sends a fetch request a get request actually is an axios to our server to that router we just saw the articles routes and then i'll grab those articles and then save it to the state object and the articles property which is an array and then we're just going to render those articles onto the screen pretty straightforward nothing too crazy here right and actually this is the only file that we're going to work on in this video is article.js file and we're going to implement that infinite scrolling logic in this file and actually first we're going to implement the logic using a class-based component and then later on we're going to factor the code to a function based components using react hooks and the reason we're going to do that is that i think that's the class based solution is a little bit easier to understand and also chances are that you might not know what react hooks are so just in case we're in first implemented logic using class based components and then we're going to refactor it to use react hooks okay and so yeah let's just start coding actually before we start coding you have to understand some dom related stuff okay so here we can see on the screen the things that you need to know so you need to know the scroll events the elements.getboundingclientrackmethod and also the window.innerheight well these are pretty straightforward to understand actually so let me explain very quick what these mean so first the screw element it fires when an element or the document view has been scrolled so let me just show you a quick demo if in the component did mount i add the scroll events so documents dot add event listener less listener scroll and then the function to run when we re-scroll and here i'm just going to say console.log we scrolled pretty straightforward now if we scroll in the browser even by a tiny bit even one pixel this event will be fired and therefore this function will get run so let's just check it so head over to the browser and open up the developer tools and go to console and now on refresh and now if i start to scroll down even just by a little bit you see that we get that console to lock we scrolled so yeah this is the scrollment and it's pretty easy to understand right so i'm just going to remove this code and the next thing that you need to know is window.inner height it's again pretty straightforward to understand let me just show you a demo if you go to the console and run window.inner height you get a number back in pixels which represents the height of the viewport which is this much from here all the way to the top of the console panel so if i increase or decrease the height of this console and i run that again you see that we get a different value and similarly we also have window dot inner width which is the width of the viewport and also something else if you open up this developer tools and you start to shrink down this width let me see if i can do that like so you see here this panel that represents the dimensions of the viewport the width and height this numbers here are the inner width and the inner height so if i stop right here is you notice here that the height gives me the width is one one one one so if i run window dot inner width again i'll just get that value so yeah this is window dot inner width next up you need to know just a moment elements.getboundingclientred so if we call that function we'll get an object like this with these values and here in this diagram you can actually see what those values represent x and left are the same thing and they indicate this distance from the left of the elements all the way to the left the left height of the viewport similarly this y or top means the distance from the top of the element until the top of the viewport and then we have this right and then the bottom and width and height are the dimensions of the elements and all these values are in pixel okay so in our case we have our viewport and we also have a container which contains some number of articles and you can see here that the container's height exceeds the height of the viewport and that's why we can scroll in our app and fire that scroll event the viewport height available to access from the window object which is this much and then we have get bounding client wrecked at bottom value of the container which is this much and as you can see here this is greater than the viewport height and as we start to scroll down eventually at a specific point these two values will be equal and that's when we need to send a request to the server to grab the next series of articles so in our event listener we need to call that fetch function again whenever this value becomes equal or less than this value here the inner height all right now that you understand the window.inner height and elements that get bound in client right and also the scroll events you should now be ready to start implementing this react infinite scrolling okay so what we need to do let me add a pseudo code here we need to add the scroll element scroll event listener and check every time we scroll to see whether or not we reached the bottom of the page if we did reach the bottom call we are called fetch function fetch function to grab the next series of articles article articles okay so this is kind of like what we need to do to implement this infinite scrolling so i suggest that you go ahead and try to do this yourself now that you understand those three dom things that we just talked about in the slides you shouldn't really have any problem coding this pseudocode just one thing here we're saying to call the fetch function we actually need to do some modification to this fetch function before we can use it because right now this page number is a static value and also here in the set state function we are actually overriding this articles property with the incoming data from the server what we need to do instead is to you know kind of merge the incoming array with the current array that we have so yeah let's do these two modifications to this fetch function so first i'm just gonna inject a variable here this dot states.page and i'm going to define it here in the state page and default it to the number one and then for this we need to merge this one with the this.stage.articles data so what i'm going to do you can either use the array.concat method or you can use es6 i want to use es6 so i'm going to create a new array with the contents of this.states.articles and also the contents of the data.article's data so yeah this is what we need to do for the fetch function so now that we've changed the fetch function you should now be able to implement this pseudocode so yeah try to pause the video right now and give it a shot okay hopefully you did come up with something so let me now show you my solution so we first need to add the scroll element here so documents dot add event listener scroll and then the function so we added the scroll elements and now let's check to see whether or not we're at the bottom so what i'm going to do is to add a statement if well what should we do here if elements dot get bounding dots sorry get bound in client right and i'm going to explain in a minute what this element is we need to define it so this is kind of like a pseudo code we need to change it in a bit is less than or equal to window dot in right here we need to send the scroll element so i'm just going to add a little console like here console.log we reach the bottom okay now let's define these elements well this element should be our articles container this div elements so we can either use an id or we can do it in a react kind of way i'm going to use refs so for that what we need to do is right here to find a new ref so this dot let's call it just container equals react dot create ref yeah that's it if you're not familiar with reactgrf just try to pause with you right now and go to the official react documentation and read this up it's pretty straightforward to understand i'm not going to explain in this video so once we defined our ref i'm just going to use it right here so ref equals this dot container and now we need to replace this with this dot container cool now let's save and head over to the browser and see whether or not it's working so i'm gonna refresh the page right now okay let's like we have an error i misspelled this event listener we don't need this k i don't know why i added it add event listener just now go ahead and refresh okay so now what i'm going to do is to start to actually oh we have another error let's see what this is oh two mistakes here first of all we need to call the current on this this dot container on this graph so current this is equivalent to calling the documents.queryselector whatever okay and then i also forgot to reference the bottom variable the bottom property of this object because remember this method here will return an object and we need to grab this bottom variable so now let's go ahead and save and refresh okay hope we don't get any error this time so i'm going to start to scroll down so yeah you see we've got this console like here we've reached the bottom and you notice here that we're getting it a lot of times actually 56 times which is absolutely not what we want we just want to get it one time because we don't want to send a fetch request multiple times right so let's fix that first for that what we need to do is to call documents dot remove event listener event and then we need to specify the scroll the event name and also the reference to function that gets called every single time we scroll so what we need to do first is to actually cut this code and move it to function because i want to be able to reference that here otherwise we can't use remove event listener so i'm going to create a new function here some call it track scrolling and this function will just do this so let's cut this code paste it right there and then instead of this i'm going to put a reference to that function to this dot track scrolling like so and i'm also gonna pass this here to start track scrolling [Music] okay now let's add back our console log let's just put yeah reached the bottom okay now let's go ahead and see what we have in the browser it's on refresh i'm going to scroll all the way down and you see that we only got it one time this time try to do that again we're not actually getting it back which is kind of expected because we're removing this event listener and we're not adding it back to the document so what we could do is to try to add this event listener again to the document object once we fetched the articles and we updated the state well as you probably guessed we need to use component did update it's a component that update and here we need to do a little bit of checking and then add this event listener right here so what we should do well remember that this function has two arguments which is one one of them is previous props we're not going to use this one and also previous states so what we want to do is to check if we updated our articles with the newly incoming data we need to add this event listener back again to the documents so i'm just going to write if previous date dot articles dot length is not equal to this dot states dot articles.length in this case what we want to do is to add our event listener so i'm going to cut this code and paste it right here [Music] okay and also i'm just going to call the fetch function instead of this console.log let's also keep this lock so i'm just going to call the fetch function this dot fetch and also remember that we need to increment this page number before we call this fetch function so what i'm going to do is here we need to actually call this dot set state to increment our page number so page equals sorry page equals well this you can't type this.page plus one and then i'm also going to pass a callback function to it because i want to run this fetch function if and only if i have already incremented the page number so yeah for that we can use callback function of this dot set state so i'm just going to move this code right here and what else we need to do actually that's pretty much all we need to do so i'm going to save here and go ahead and give it a try some come here and refresh okay i'm going to start to scroll down and you can see that here we're actually fetching the articles and we're rendering them on the screen if i go to the network tab let's actually refresh again okay you see here we send our first request to grab the articles of page one then if i start to scroll down if i reach the bottom of the page you notice that we send the next request and if i keep going you see that we're constantly sending requests to grab the next series of articles and now i'm at the bottom of the page and you see that here we send 10 requests for 10 pages that we actually have hey this is me from the future and after creating this video i noticed that i forgot to add one more thing to our class b solution and that is to remove the scroll events scrolling wetlistener once we unmount the components and the reason we're going to do this is that imagine that we had more components more pages in our application and if we don't remove this event listener and we change the page we always going to have the scroll events which is a bad thing for performance so what we want to do is well that's pretty straightforward right here we just need to add components well unmount this component lifecycle method will run each time our component unmounts and all we need to do here is to remove that event listener so documents dot remove event listener scroll and then this dot track scrolling okay that's it okay so at this point our infinite scrolling is pretty much complete but i'm going to do two more things first of all i'm also going to show a loading just to give an impression to the user that hey we were actually doing something in the background so let's do that pretty quick it's it shouldn't be really that hard so right here in the state object all i'm going to do is add a loading loading property and i'm going to default it to true because we need to show the loading icon when we start the app and what i'm going to do is here in our fetch function right here i'm going to set that loading icon excuse me i'm here loading property to be true and then right here once we sent the request and we updated states i'm going to change that loading to be false set state loading false and the last thing we need to do is to show that loading icon so right here i'm going to show that loading actually i have already implemented the loading icon it's available in this file loading.js so i've grabbed this code from this website they have a couple of cool pure css loading icon so if you want go ahead and check this out and yeah this is just loading so we first actually have to import it so i'm going to say imports loading from dot slash loading and i want to show it here loading sorry we have a typo there we go i'm going to show it right here if this dot states dot loading show the loading components like so okay now let's save and refresh the page i'm actually gonna what i want to do is to set the network speed to fast 3g we want to be able to see that loading okay and there we go now let's start to scroll down there you go once again again and again cool so i want to do one more thing and that's to show a message right here to the user that hey there is no more articles to fetch you have already reached the end so for that what we want to do is right here add another priority to our state object i'm going to call it let's call it has ended and i'll default it to true actually false of course false and i'm also going to add a comment here to indicate whether or not we've reached actually we fetched and say we've fetched all the records okay and the places that we're going to use this is well first of all here in our fetch function so what we can do is have if statement here to check if this is an empty array that means that we are done okay if you come here and take a look at page not 10 the last request we sent you see here that this property here this article's data is an empty array but here and here we have some data in that race so we just need to check that so if data dots articles data dot length is equal to one actually zero to set that property so this dot set state has ended to be true okay and let's also add an else statement here and only run this code if the length is not zero okay and then i'm going to show it here show message here if this dot state dot has ended well what we want to show is let's show a div and actually i have already implemented this the style of this div element so we need to give it a class name of end articles message make sure that you type exactly this we have this class right here in public and then style.css i have already added it right here okay now i'm going to close the stiff and let's also show a message a p tag and what should we show well let's say you're all caught up well it probably doesn't make sense to have this message in this application but that'll do it that'll do it okay so let's save and refresh again i'm gonna set it back to online and i'm gonna start to scroll down down down to reach the bottom i mean to reach the ends and there we go we have this message right here you're all cut up okay cool so this is pretty much complete the class based solution and as i promised now we're going to go ahead and refactor this code to use react hooks so i'm going to change it to a function based component okay so now let's go ahead and refactor our code to a function based components instead of class based components if you're not familiar with react hooks such as use state use ref and use effect positively right now and go ahead and try to read up some documentation on what exactly our react hooks well i'm sure there are countless great tutorials and youtube videos out there talking about react hooks so if you don't know them make sure to pause the video right now and go ahead and try to go watch some tutorials some blog posts documentations or whatever okay so let's refactor our codes first of all i'm going to import some hooks so instead of its components i need to import use state we also need to import use ref and the last one we need to import is use effect [Music] okay and now let's change this from a class-based component so function based components so cons articles equal to a function well we obviously need to remove this constructor so i'm going to do that now instead of this we need to use use state so i'm going to fast forward a little to type all this code out [Music] okay so i used use date to be able to use all these variables that we have right now so i'm just going to remove this.state and also i need to add a const here [Music] and remove this and i'll actually just use riff yeah use ref instead of react.creatref we need to use react dot oh sorry just use ref and next up actually i also need to pass null and now let's change our component life cycle methods so what we can do is to use effect hook actually i'm and i'm not going to explain what use effect is go ahead and read it up if you want i'm not going to teach you react hooks in this video but basically just kind of like this component that mounts and component did updates we use it and we also need to pass something here so in this case i'm going to pass page now this means that whenever we change this page state this one run this function so what we want to run is you know well just fetch okay yeah we just need to fetch and actually i'm just going to add an if statement if not has ended fetch okay and also i'm going to return a function this is this will act kind of like the components will unmount we need to do our cleanups here so our cleanup is to run documents documents dot remove events listener our scroll events needs to be in string scroll events and track scrolling okay we also need to use another use effect so i'm going to call it again here and this time we need to call it every single time we change our articles okay articles and what we need to do here is to add the event listener so documents dots adds event listener scroll and then track scrolling okay so that's it for our component lifecycle method so i'm just going to remove componented mount now also going to remove component did update and yeah that's that's it we need to add a concierge well let's see what else we need to do this fetch function so i'm going to say const fetch equals this function [Music] okay and now we need to update whenever we have this dot set state so let's start from the top of the page right here what we want to do instead of this we need to say set page and we also don't need to call the fetch function in the track scrolling method because well whenever we call the set page so let me just remove this we are calling this function again this use effect function and there we are actually calling the fetch function it's a little bit cleaner right so yeah this is set page and then what else we need to do now let's move on to the fetch function instead of this i'm just going to say set loading and then where else we have it here we need to say set has ended and right here we need to say set articles okay your set loading oops loading then render articles i'm to change it a little const this equals this okay that's pretty much it oh and so we also need to remove whenever we have this that sets this dot state so i'm just going to select it and hit command d multiple times select sorry we need to oops okay i want to hit this multiple times and just remove them cool oh we also don't need this render function so i'm also going to remove this let's see if all is good yeah we also need to remove this this dot whenever we have that so i'm also going to hit command z multiple times and there we go deletes okay hope we're done i want to save right now and head over to the browser and see what we'll get so i'm going to open up the console to see if we get any error and i want to refresh i hope we did get some errors articles.map is not a function let's see what we're doing wrong here's our articles where was this error in the render articles okay so we're returning articles.map well okay not sure what exactly is going wrong oh i get it now we also need to remove this stuff so let's do that right now i'm actually let me just do this okay okay we also need to remove these there we go whenever we have these kind of set states we need to do that set page to this then where else we have these sets i'm just going to search for set set loading just true next we have your set has ended just true again here just false set articles already done again search for set let's see what we have set page is correct said loading is look correct so it has ended correct correct correct okay we should be done now i'm going to save again head over refresh and start to scroll down and there we go it now works but this time we're using react hooks cool okay so now this is a solution using a function based component components alright that's it for this video and thank you so much for watching if you enjoyed and learned something new in this video please hit the like button and share it with other people also if you have any questions make sure to post them in the comment box down below also make sure to subscribe for more content while actually not like this video i was a bit reluctant to drop this video because well this channel is all about fundamentals of software engineering and computer science and well videos are supposed to be challenging and this video was pretty much all about react well nothing so fundamental but anyway i just did it and also this channel is just getting started there's a lot of cool stuff coming up like how to manage an application with millions of users some core c plus plus stuff some challenging apps to build how to use multiple program languages and databases for a single app and a lot more content but actually this stuff are not coming up in the next week or third about they will probably come in a couple of months so a lot of plans and ideas for this channel so make sure to subscribe to follow ok i'll see you in the next video
Info
Channel: Cododev
Views: 977
Rating: 4.5999999 out of 5
Keywords: React, JavaScript, infinte scroll, infinite scrolling, react hooks
Id: JbhCsuWu8cg
Channel Id: undefined
Length: 38min 59sec (2339 seconds)
Published: Tue Feb 09 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.