How to fetch data from an API in ReactJS or NextJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay guys so welcome back again so in this video let's have a look at the data fetching library called hwr and basically this library is my go-to library for any of my react or nexus projects so this library provides us with a hook called use swr and then we can use that hook to make api calls to our resource server so for the purposes of this video i would be using this jsonplaceholder api which provides us with resources here if we scroll down we can see that if we go to this url that is forward slash users we will get back a list of 10 users so that's what we are going to use inside this video and if we have a look at one more thing that is let me copy this url and let me paste it here and if we simply append one here we see that we then get back a single user object here so this is the fake rest api which we are going to use inside our application as of now for to demonstrate how users wr works so without wasting any time let's jump into our code and the first thing we need to do before jumping into code we need to see that how do we install this library so for that we can simply go to docs here so if you are using yarn you can simply do yarn and swr or if you are using npm then you can simply use npm install swr so let's go to our vs code here and here what i've done is that that i've created a very basic react project using create react app package which simply provides us with this skeleton here for a react project and currently i've stripped down the app component here and it currently displays data fetching using use swr hook as we can see here on the right side and now if we go to the package.json file we see that here we have the dependencies here but for this project i have installed two more dependencies that is the swr library itself by doing npmi swr and it is super simple to do and then i've installed one more dependency that is not exactly needed by swr but that is again my go-to dependency whenever i'm using the swr library so i've also installed this library called axios though you can use the browser built-in fetch api you can use that fetch api but i always go for axios because for me it's like bread and butter for any react or nexus application or for kind of any web application it's my go to library again so we would be using swr with axios and you wouldn't be getting to know that why do we need axios here in case you are not needing in case you are not using the fetch api so let me close the package.json file and the first thing we need to do we need to instead of doing anything inside this app component what i would like to do i would like to create a new component inside my source folder here which would be containing the data that is coming from that user's endpoint so why not let me simply create a new file and here let me simply call it users component dot jsx though you can call it js or j6 whatever you feel like but for me it's better to call it jsx and now what i'll do is simply create a functional component here called user component and it would simply have an h1 here and that should simply say user component like this and now let me import this user component inside my app.js file and you would be getting to know that why i've created this separate component here in a moment so user component like this and this is automatically imported here from users component so let's save this and let's run this application if it is not started here so we do not see that users component here or do we do see that users component here so we are seeing that user component here so why not to let's take this user component out from this app header so that it is somewhere here and now let's go to our user component and all the magic happens in this component so firstly what we need to have is that that from that swr library we need to import one hook and that is the use swr hook so what we will say import use swr from swr and now we would be using this hook to fetch data from that url so firstly let's go to that url to get the url in point so let's simply copy this inside our clipboard and now here what i need to do i need to use the use swr hook which we just imported so what i'll say i'll say const something equal to use swr and now basically this hook returns us a couple of values here inside this object which we would be seeing in a moment but firstly this use swr hook accepts at least two parameters or in some cases even a single parameter but here the first parameter you need to provide here is the key and in our case the key would be the url endpoint from which you want to get data from so i just copied the url endpoint and that is this endpoint that is this endpoint you get the data from and then it expects a second argument and that is called a fetcher function so fetcher like this and now what this feature function does it simply returns the data that is associated with this url endpoint so let's create this feature function somewhere outside this component here so let's create that feature function here so const fetcher equal to an arrow function like this and this should return some kind of a data and that data would be provided by this usw library inside the data object here like this simply like this so how do we get this data here that is from this feature function so to do that what we need to do we need to pass some kind of a url inside this feature function and now that is the magic of this use swr hook that is whatever url or key you provide here would be automatically passed to this fetcher function so here we can simply say that this is a url that is passed here and how to get data so to get data what we are going to use we are going to import axios from axios so that's why i said that i am using axios here though you could have used the fetch api also and here what we can simply say we can simply say axios dot get we can pass in the url and then we have a response so response like this and then we can simply return response dot data and now this response dot data would be available inside this data parameter here inside this object here which is returned by use swr hook and in case if this request fails that is in case if this request throws some error then we do not need to manually handle the error uh always like using the catch block but if you want to do some more stuff with this with the error handling then you can definitely handle the catch stuff but by default if this uh if this request throws us an error then this uswr hook would also automatically handle that and that would be provided in the error object here that is if there is an error to get this url then it would be present inside this error object which is provided by this uswr hook so that's all what you need to do to get data or error from this use swr hook and now how do we uh how do we know that whether we have our data whether we have an error or whether we are currently in the process of making a request that is whether we are in a loading state so to do that it is very simple again firstly we need to check if there is an error so we'll check if error if there is an error then what we need to do we need to simply spit out the error here and here we can simply say error dot message like this and now if there is not an error then there might be a case that we are currently in the process of making a request and we are in a loading state we neither have data here we neither have an error then what we can do we can simply make an if check again that is if not data that is if there is not a data if there is no data and if there is no error then what we can do we can simply say we are in a process of loading here so here what you can do you can simply show in a skeleton or something like that but here i am simply outputting loading here inside the p tags and now finally if there is no error and this is also false then we are finally here which means that we do have data so to display data what i'm going to do i'm simply going to use free tags to display the json output here so we can say json.stringify data comma null comma 2 just to make a beautiful output here and now as soon as we save this application you see that on the right side we should be getting the array of user objects here inside this user component so let me save this application and we see that we have this data that is coming from the jsonplaceholder api and now if i reload the page you might be seeing a flash of loading message and this should not be like this this should be like uh it should be like a return it should be like uh return uh this thing here and the same thing goes for this thing again that is it should be returned like this and not directly p tags like as it was before and now if i reload the application once again we should be getting a flash of loading here so we see that we got loading of loading that is flashing here or instead let me put it in h1 here so that we can see it more clearly so as soon as i do it we are not able to see it so what i'll do i'll simply go to inspect and i'll simply reduce my network speed so that we can see the loading state here so let me go here that is throttling and let me go to slow 3g and now as soon as i reload we should be getting a loading state here so we would be seeing that so so we see we are get in a loading state and now finally when there was no error and we have the data we see this uh this data object here so now let's see that how do we see the error so for that it is pretty simple to do let's let me simply change this url which doesn't exist and it should throw us a 404 so let me save this and here as soon as i reload the page we should be getting a error here that is 404 not found so we see that we are getting this message that is request fail with status code 404 because this route does not exist so this is the most simple way of fetching data using the [Music] uh use swr hook now let's have a look at some more things which you can pass to this uswr hook so currently if we go to this library page here and if we have a look at the options here the third parameter inside this swr hook which we can pass is an object of options here and options there are so many options which you can pass here but i would simply go through a couple of them because they might be useful to you so let's go back here so let's go back to our application and here what we can do we can pass in a third option here or a third parameter here containing the options object so currently watch what happens here so let me open another tab here so let me simply open another tab here and let me open the window here that is inspect and let me go to the network tab here and let me reload the page let me clear out the console and now you see that we are inside this user component so if i simply change the window here to some other window inside my browser and as soon as i switch back to this react application or to our application where we are using this swr hook we would be seeing that a call should a call is made again to the endpoint to revalidate the data as we can see now we have these two users here so let me delete it once again and now let me switch back to another window and as soon as i switch back to this react app window we see that we are again revalidating the data as soon as this window is in focus so this is one of the most interesting parts or one of the most required parts for any application that refreshes the data as soon as the window is in focus though you can disable this behavior also by simply putting in an option here that is revalidate on focus to be false by default it is true but if you simply pass and revalidate on focus to be false then you would not be revalidating your data whenever this window is in focus again so let me save this and let me clear up the this thing here network request and let me switch another window let's go back to our main window again now we see that since this revalidate on focus is false so we do not make an another network request so this is something you might use or you might not use so now let's have a look at another option here and that is refresh interval so let me write it first so let the refresh interval be 1000 milliseconds that is this value should be in milliseconds so it is one second as of now what this refresh interval does is that that suppose you have a web application in which you want to have real-time data from the back end so typically you might have been using web sockets but with this library you are not required to use web sockets if that if web socket is uh is an overkill for your application so what you can do you can simply pass in refresh interval 1000 and then in an interval of one second that is in an interval of 1000 milliseconds this library would again and again fetch data from this url and we would be seeing that in a moment as soon as i save this application so let me save this application so we see that we are making network request in at every one second here we see that after every one second we are making a request to this url endpoint so this is one of the things which sometimes i use in my application though i prefer to use web sockets but sometimes websockets is an overkill so then you can simply use this refresh interval parameter here or an option here so let me comment it out and now here what i am going to do i'm going to create one more component here which would simply fetch us the a user by id thing here that is currently we are fetching an array of users we are simply going to fetch user with an id but before doing that what i'll do i instead of simply stringifying it here like this what i would do i would simply map this data into some paragraphs here so that we can only see the name here on individual items here so that i have more speaks to work with so what i'll do i'll simply say data dot map and here we have a user and here we simply want to return a p tag that is a paragraph so p and here i would simply out i simply want to output the user dot name thing here and this should have a key and if you do not know how to work with react.js list then you can watch my video that is linked above that is a bigness course for react.js and here i can simply provide an user.id like this and now we would be seeing only the username here inside the list here as you can see here so now what i'll do i'll simply create one more component here or before making a component here let me show you one more thing and that is the mutate mutate function which is return from this usage wr hook so to handle that thing what i'll do is simply create a button here so button like this and let's simply call it refetch data re-fetch data for some reason it's a dummy button so i'm simply calling this button like this that is refresh data for some reason so we have this button here which currently does nothing and let me clear the console so now this use swr hook returns us a couple of more objects apart from this data and this error thing and one more thing that is returned here is the mutate function so it should be like this error comma mutate like this and now what this mutate does is this that it simply refreshes the data from this url endpoint programmatically because currently there was no way to revalidate the data programmatically either you need to pass that as an options here with a refresh interval but to refresh the data programmatically what you can do you can use this mutate function and this mutate function that is returned by this uswr hook is bound to this url so whenever you would call this mutate function it would simply make a call again to this url so here let me simply handle this button click here so i can say on click on click equal to an arrow function and it simply calls that function that is mutate and again this mutate is bound to that this url here that is to this exact hook here and it would simply use the same url and the same feature function here and the same options as well though you can manually change the options here that is by passing in the options object here but i am not going into that details because that is some advanced stuff but here let me simply do it like this so let's save this and watch what would happen as soon as i would click this button here so we see that currently our this network log is empty so as soon as i press this button we see that we are having this thing here that is we are making a request here so let me clear out once again so let me click this we see that we are making a call to this user's endpoint here we see that we are making calls to this user endpoint so let me click it again and again we see that we are again and again making a call to this user's endpoint to get or re-fetch the data from this endpoint so this mutate might be useful for you if you were having some data here and you made a post request using any library like axios or fetch to update the data on the back end and then you want to revalidate the data on the front end with the new data that is present on the back end then after making a post request you can simply call this mutate function to refresh the data from that back end so this is again what you can do and now let's have a look at another thing so let me comment this mutate out from here and now let's have a look that how do we conditionally fetch data from this endpoint or from any endpoint so for that what i'm going to do i'm going to create a new component here and that would be the user component currently we have the user's component and now we would be having a user component or let me call it individual user because it would be like more intuitive so individual user dot jsx like this and now i'll create a functional component as before and i would again import the users wr hooks so i would say import uh from swr i want to import the use swr thing like this and now what i want to do is this that i need to pass some kind of an id as a prop to this individual user component and then i want to fetch data for that particular user because if we have a look here to this placeholder api if we simply pass in forward slash one to this url endpoint then we would be fetching data for this particular individual user so let's do that so let me grab the url here that is this url let me simply copy this everything from here because we only need to make some minor adjustments here so let's copy that and let's paste it here and here we see that as soon as we are inside this app like inside we are using this swr hook inside this uh separate component we see that we need to have the feature function here as well so we what we can do we can simply create this feature function inside it's inside its own file somewhere inside our application and then we can export that fetcher function as a constant which to be used inside any of the components so for the for simplicity let me simply export it as a constant from this file itself that is from user component.jsx itself though it should be in its own file so now i can import this feature from that user component.jsx so let me import it so now we have this feature function and now we do not need mutate here we only want to have the data here and the end point would be this end point forward slash it should be in back text because i need to change this i need to change it to a template string and here i need to pass in some kind of an id here that is the user id and this user id comes as a prop to this component here like this and then what we can do we can again make f checks here that is if error if there is an error we can simply return p with an error message so we can say error dot message like this if there is not data that is if the data is if the network request is in progress then we can simply return here loading so we can simply say p loading like this otherwise we can simply return the data here and in the data we can again use the pre-tax to return the data here so let me simply call it free and here we would be simply saying so just json.stringify data comma null comma 2 like this so let's save this and now let's uh let me close this network tab here so that we have some more space here so now let's go to our user component and here what we want to have is this that whenever someone clicks on this uh on these uh items that is these names we should be seeing that data inside this uh new inside this individual user component so what we can do we can simply import this new individual user component inside our user component so we can say individual user like this and now this individual user has been imported here from the individual user and here we need to pass in some kind of an id here because that is the id or the prop which this component expects and to store this id what i'll do is simply create a state variable inside my user component.jsx so let me create a state variable here at a very at the very top so let's say use a state and the state would be the id of the or the user id and the initial state would be null that is there is no user id and we also need to import the user state from react so we can do that so we have this user state from react so the initial id is null here so we can pass that id here like this and now whenever someone clicks on this i uh this uh name here we want to set the id according to the user id here so what we can do we can simply handle the on click listener on this p tag that is on click we can do it like this we can simply say set id to be user dot id like this so if i can give me some more room here we can say that we can see that we have this on click event on this name thing here so now this id is passed here but let's go back to our individual user component and now here we see that we are passing in this id here and we see that we are getting back an error of request code field with 404 and to make it like more explicit what we can do we can wrap this uh thing inside its own div and we can give it some styling here so that it is like more prominent that what the individual user component is and let's give it a background color of so background color to be like let's say uh light gray or light gray like this so you can see that uh let's also give it a padding of something so padding would be let's say 16 pixels so we see that we have this oh i click this name here so we are getting the results here so let me refresh the page and we'll get back to it again so we see that we are getting this message here that is request code field a request field with status code 404 and that is because initially the user id is null here and we are making a request here to this url endpoint that is forward slash users forward slash null and which does not exist so even if we go to this json placeholder api and instead of one if we simply pass in null here we see that we simply get back an empty object here but this is a 404 error and this might be validated here as well so network request so let's reload we see that we are getting back a 404 error here from this endpoint that is users null is a 404 error and that's what we are seeing inside our application that we are getting this error so what do we want to have here is this that we want to conditionally fetch data depending on this id that is whether if this id is present then only fetch the data from this endpoint so to do that what we can do we can simply make an f check here that is using the ternary operator of course that is if there is an id property or the id prop present if it is not null then make a request otherwise simply pass in null as the key here so now what would happen is this that we won't be even making a request to this endpoint with the null value if this id property is not present and instead it would only make a request whenever this id property exists and then only it would make a request to this url endpoint so let's save this so now we see that we are getting loading here and that is because this id is null this request is not made we do not have the error neither do we have the data so therefore we are displaying loading here so you can write some more f checks to display data accordingly but i am not going into that detail but here i would like to show you one more thing that is a request to this url endpoint is not made by this usswr hook so if i right click and click on inspect and if i go to the network tab again and if i reload the page we see that we are not making any request to that endpoint that is forward slash null which initially we were doing so so therefore we were getting the 404 error but as soon as i clicked here i clicked on this i guess that's i guess i clicked on this this second id here so therefore we made a request to this two here and if i click on one this thing here we are making a request to this one if i click on this thing here we are making a request to this five and if i close this network request we see that we are getting data as soon as i click on any of the items here or any of the names here we are making a request and we are getting data so this is how you use uh conditional fetching from this uses wr hook and now one last thing is this that currently we see that we are using this feature function in each and every uses wr hook inside the user's component as well we are making a use of this feature inside the individual user also we are making a use of this feature here but there might be some easier way so that we should not pass to this feature function to each and every usage wr hook so there can be a global place so let's go to our app.js and here we have the users component and inside the users component we have the individual user here so let's see here we have the individual user here so what we can do we can go to our app.js and here we can import something else and that is import something from swr and here there is a thing called swr config like this and now what we want to do we want to wrap each and everything which requires that feature function or the different options which we can pass inside this swr hook which we were passing currently here inside these options directly to this swr config so what we can do we can simply wrap our application inside this swr config so swr config like this and then we need to wrap this application inside this swr config and this swrcone fix takes in a value prop and here we need to pass in the fetcher function so the feature would be it should be like this so we need to pass in the fetcher function and the fetcher function is our fetcher function coming from the user component so let's uh extract this uh let's uh cut it out from here and let's paste it to inside our app.js and now we do not even need to export it and you'll get to know why and let me input axios here and now we can simply pass in this feature function like this here and now we are passing this feature function here so what we can do we can go to our users component and now we do not need to require we are not required to pass this feature here to this compo to this hook because it can directly take that from the swr provider that is this swr config so we can remove this feature function from here so let's remove it and let me also remove the options from here and in the same way we can go to our individual users here again we do not require the fetcher function because it is a part of that reactory from where that swr config is providing in the fetcher function and we can remove this unwanted line from here and let's see if this let me remove this as well and i guess that that's pretty much about it and now if i click on this this thing we are able to fetch data because we have provided in the global feature function for this swr config though if you want you can override this feature function that is this feature function in any of the components wherever you use this use swr hook by providing in the second argument and that is the feature function and that feature function can be different from this feature function and similarly you can provide in some options here so here let me simply say refresh interval to be one second so this refresh interval would be the default interval for each and every hook that is a part of this that is like a child of this swr config so this user uh so let's go to our network tab and we would be seeing that we are going to make like multiple requests to this thing here so we see that we are again and again making request to this users and this eight route because we are using the default google global refresh interval of once again so guys that's all about this video so if you like the video do hit the like button if you haven't subscribed to our channel do subscribe to the channel so thank you bye bye take care and have a good day and have a great day
Info
Channel: Mafia Codes
Views: 6,624
Rating: undefined out of 5
Keywords: data fetching in nextjs, how to use the useSWR hook, useswr hook, how to use mutate in useswr, how to fetch data in reactjs, stale while revalidate, swr hook, swr react hooks, swr mutate, useswr, useswr next js, useswrinfinite, useswr mutate, useswr pagination, useswr vs fetch, useswr vs react-query, useswr with axis, what is a fetcher function, fetcher function in swr
Id: EDU4HwNzmsY
Channel Id: undefined
Length: 31min 41sec (1901 seconds)
Published: Tue Nov 30 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.