Fetch Data from API in React JS | Learn ReactJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome hi i'm dave and this tutorial is part of a learn react tutorial series i will link to the playlist with the full series in the description below in the last tutorial we learned about using json server to run a local rest api as a development server where we could work with it and use that rest api as we develop our front end and that's what we're going to use today as well so you can see i've got visual studio code here on the left and on the right i've got chrome open i've got the grocery list application we've been building in the top right i've already got dev tools open the console is available here on the bottom and i've also opened a bash window here at the bottom of visual studio code in the terminal and this is the window i'm running react in of course with npm start now we need to open another terminal window to go ahead and start the json server and if you remember from the last tutorial instead of npm we use npx and then we say json-sir and then dash p for port and i'll say 3500 w for watch and then we say data slash db dot json and that is because we have a data folder and in here we have our db.json i'm going to give a link to the source code for this tutorial that will be on github so if you don't have this json already the starter information you can easily get it from the link to the repository in the description okay i'm going to click on the app file so this is where we're going to do the work today but i need to press enter down here to start the json server and when that finishes we will be ready to go it'll take just about a minute and i'll be right back okay with json server now running i'm going to click the little up arrow here just beside the x in visual studio code to expand the terminal window and scroll just a little so we can see some information it gives us resources it's running a local host with the port 3500 as we specified and then we're getting our items so this will be our root url that we will contact with the fetch api to get information so i'm just going to copy that and then i'll go ahead and click the down arrow and then we can just x out of the terminals they'll continue to run the server and react for us and we can display those again if we want to but now just under the function app here for our app component i want to put a const and put the api underscore url and i use all caps for that because this will be a constant in the true sense of the word where this url will not change for us so we can refer to it as we create the different fetch requests and i'll put one line after that and go ahead and save the file and after that we can look at our use effect and let me go ahead and press ctrl b as in boy to hide the file tree and then i'm also going to press alt z so it wraps some lines of code like you see here on line 11 where this line of code would be longer and it just wraps it down and then line 11 takes a little more space again that's alt z as in zebra okay now that we've got that going i'm going to look at use effect here and also this use state because we're loading our current data from the local storage as we had in previous tutorials and for some reason if we didn't have a shopping list like say the reason would be we hadn't ever accessed this application or a brand new user we at least need to load an empty array so we don't get errors by trying to access properties of the array from our code so instead of getting this data from local storage now we want to just go ahead and remove this loading part and the short circuit or operators but leave the empty array for the use state and that's the state we want to initially load the application with and then we will switch down here to the use effect and where we're saving these items and listing for any changes in state in the use effect dependency to items we can get rid of all of that as well because we're going to use effect with an empty array as a dependency which means what happens in use effect will only occur at load time because we only want it to happen that one time and that's when we would load the data from the rest api and after that we can manage it in state but then we will send messages back to the rest api to keep that database in sync with our current state of the application now because we want to use async await it's important to note that we cannot do this with use effect uh async won't work that way with use effect and so you will often see uh the old way of using fetch inside of use effect and that will chain venables as you would use fetch and put in the url and then have a then afterwards and possibly another then and so on we're not going to do that we want to use async a weight and so we need to just define an async function that we can call inside of use effect now we could define that function outside of use effect and then call it in if we wanted to use that function elsewhere as well because then it would make it available to the rest of the application we're not going to though because we only need this function inside of this one use effect call at load time so i'm going to define fetch items and make this an arrow function and of course we need to put async right here and now that we have determined that fetch items is an async arrow function we'll start with a try block and then of course you want to end a try block with a catch block and we would catch any error and so in the try block we want to put our fetch statement and we'll define a response that we expect to get and we will await a fetch call and here we will just need to fetch the api url and this full url right here if you were to paste this inside of chrome it would of course perform a get request by default and it will return those items inside of our db.json and those are running from the rest server the json server so we get this response and after we get a response what we would typically do is say okay these are wait a minute lower case here these are our list items that we want and here we'll await the response to convert to json just call the json method and there we would have our list items and then we can set our items to the list items and that is typically what we would do to get the information now we need to think about the error as well we would get an error here so for now let's put a console log and just put the error that we would get or let's do the error stack so we get the information let's go ahead and log this information to the console as well up here just to make sure we're getting these list items from the json server we're going to modify this fetch just a little bit as well but right now i just want to start with this information so let's go ahead with this but look we're not calling it yet so how do we call this async function inside of use effect well what we need to do is of course being an async function it kind of needs to be called in its own async so we're going to put in an instantly instantiated async and here we can call fetch items and await the response and so we'll say await fetch items and then we need i believe no we've got the two parentheses there so then we just need at the end the operators to call it into action and after that we'll go ahead and save and see what we get okay so we still loaded our items because we set the list items and also it logged the list items to the console as we see right here i'll bring this up just a little to have some more room and we can see the list items right here so this worked as we expected it to now we're not updating anything yet at the rest api so if i change the state of the application here such as checking bread we don't see that changed here check did not turn into true this just loads at load time because this is in use effect and it's an empty array so it just happens the one time we're not going to see this reload in the console and have console changes here it only happens the one time so if there is another change in the state of the application a re-render we still won't see this operation happen again because once again this use effect operation will only happen at load time now let's go ahead and cause an error and see if we get that back in the error right here as we would log it to the console so i'm going to go up to this url i'm just going to put an extra s here so it will not find the url and let's go ahead and save and we should reload the application and we've got an error in the application because it says items.filter is not a function and so we didn't really catch the error here at all in fact it actually produced an empty list or a null list if you will and then we set this to empty essentially null and then we couldn't use the filter on items like we have in jsx it's a it's trying to call an operation on something that doesn't exist and that is the error so if we look back up here get past all this error code i can bring this up a little more way back to where we were you can see we got a 404 not found response and that wasn't logged here as we would see on line 24. it's actually an error that comes from the response we did get a response and then line 21 went ahead and executed here and we logged the list items which was just empty and it's not an empty array so we actually need to do something to catch this type of error as well what we're going to do is set up a fetch error with state and so i'll define say const and then here i'll say fetch error and then of course set fetch error and we'll use state with this so we'll say use state and we'll just set it to null to start out i guess it wasn't using semicolons after all that i've been a little inconsistent let me go ahead and add the semicolons here just so i can stay a little more consistent okay so we've got fetch error and set fetch error and now what we need to do is after we get this response and before we set it to list items we need to look for an error so we can say if response okay but what we really want to do say is if the response is not okay now our response dot ok is equal to a 200 response or a response in the 200 range which would indicate an http status of okay and then if it's not okay that means we got something like a 404 as the response and so now we're going to throw an error and i'm just going to say did not receive expected data as the error message and then that would come down to this catch block so then we would actually see this error caught and let me go ahead and clear the console and then i'm going to save this and we'll leave this extra s in items so we still get the 404 error but let's see what happens now we don't get that huge list of errors in the console what we do get is the 404 but then we catch the error and the error is put here did not receive expected data so that works to catch our error in the fetch and instead of the stack now let's just log the message property here i'll save and it should do it again and now we get did not receive expected data instead of error did not receive expected data so it just made it a little bit smaller a message overall of course it's warning us that fetch error and set fetch error have not been used yet and that's what we need to do is handle this error so we're going to set the fetch error here if we've had a successful request after we list the items and we will set it to null because previously we might have had a fetch error set that was not null so we want to make sure that we're setting it back to null here and then as we catch this error we don't just want to log to the console we want to set the fetch error and here we'll set it equal to the error message and then we can go ahead and get rid of this console log because we have got the fetch error saved in state and then after that we should save now we won't see this logged here now but we do see the 404 error in the console anyway but let's use this fetch error in our jsx to indicate to the user there has been an error and we can deliver a message based on that so down here in our components here's the return with all of the jsx our content if you remember really contains the main element and then the list items that go within the main element so what we can do is before the content we'll put the main element here and then i'm going to just take the closing main element and put it under the content and then highlight the content and tab over we'll save that it hasn't really used fetch yet or the fetch error yet but we will in just a moment i'm going to press ctrl b to show the file tree go to the content.js component for just a moment and instead of having the main element here i just put it into the app jsx we'll just make this what they call a fragment so in react you can have a fragment and here it doesn't have an element inside it but you need to have whatever you put in the jsx inside of a parent element or an element container and you can use a fragment to do that so it has a closing slash inside the less than and greater than and then just the less than and greater than with nothing in it is considered to be a fragment so we can save it like that and continue to keep the main element right here in the app component jsx okay now that we've made that change i'm going to press ctrl b to hide the file tree again and we can use the fetch error right above the content now and so i'm going to put the curly braces to indicate this is an expression and we'll say fetch error and that means okay we have an error now and then i'm going to put two ands the ampersand and so if we have a fetch error we're going to and now i'm going to put a paragraph here simple paragraph that we'll have in the main element and we will say error inside of curly braces with a template literal i'll say error and now we'll put in the fetch error and close that now we'll use the back tick to close the template literal then we'll have another curly brace because we're inside of the paragraph here okay now that we've got that expression let's go ahead and add just a little bit of style to this paragraph as well so i'll put in style equals curly brace now remember this is indicating an expression we need another curly brace and now we can put in the actual css properties and i'll put color and then red in quotations i'm going to press alt z to wrap as this got just a little bit longer wait a minute it's not wrapping there it is maybe it was already wrapping so the closing paragraph is right down here but we're just switching the color to red and i'll save that and now we can see our error displayed up here error did not received expected data oh i've got a typo there that is not correct i just want to say did not receive expected data let's save that now that looks correct did not receive expected data back in the jsx we can also prevent this your list is empty or if the list was not empty and we still had some error that would display we can prevent that from showing and we can do the same kind of thing we did here with this error message but in front of the content we'll put a curly brace and i'll say if no fetch error and we indicate that with the exclamation mark once again two ampersands and then we'll have the content but then of course we need to put a closing curly brace at the end of the content and now only if there is no fetch error if fetch error state is false then it will display this content component so if we save now the year list is empty message disappeared likewise we can come up here and fix our url and save and now we get our list items and of course they were logged to the console again as well so we have no error the error message did not display but the content component did okay our fetch request is working and we are catching errors including response errors that wouldn't normally be caught by the catch error block here in our try catch block however there's one thing still missing and we need to realize that an api may not be as fast as a rest api that we're running in a local environment like we are with json server so let's kind of simulate that by using a set timeout here in our code so i'll start the timeout and then it has an anonymous function and inside this function we can put our async call to fetch items and we'll make this wait two seconds before it makes the async call now i'll save this and let's reload the application now it says our list is empty and then we get the items so what we want to do is not have a false message saying our list is empty when it's really not we really want to tell the user the list is loading or that we're loading the data or some message like that when we're waiting on the api to finish that initial call so we're going to use one more piece of state and we'll do that up here at the top and we'll define const and here we can say is loading and then of course set is loading [Music] and after that we'll set it equal to use state and this will be a boolean either true or false and when the app first loads first render it will be true because we plan on loading that data so we don't really need to set it down here we're not reusing this function at any other time anyway so this is just based on the loading state we'll set it to true but then after everything completes we can with with a try catch block we can use a finally at the end and here we will set is loading to false and now we can save this and we won't see a change yet because we're not using it in our jsx but we are tracking the state of loading and we do not set it to false until everything is completed in this finally whether we've received an error or the fetch is completed as we want it to so now in our jsx let's go ahead and utilize this loading state as well once again inside the main element that we've provided we can put a curly brace and we can say if we have i put loading is loading so if is loading is true then let's go ahead and show this and this is just a simple paragraph and we'll say loading items and that's really all we need we're just going to show loading items if is loading is true but we don't have to worry about our error block this will not show unless we have an error so we'll leave that as is but here with the content if fetch error does not exist we've been showing the content component but also we want if is loading is false and now the content component will only show if there is no error and if we are not loading so this is what we want so i'll save this so let's go ahead and reload the application now we get loading items and then the items appear so just in that brief time that we're waiting on the items during the load in use effect and again we simulated that loading time with our timeout here you do not want this in your code this is just a simulation but you can do it just for now to simulate that loading time and again that's slower than you would even expect from a server but it allows us to see it we hit reload we're loading the items and then they show up let's go ahead and remove the console statement out of the try block as well and there we have the completed async function of fetch items and it is only created and called the first time the app loads and use effect and the other benefit since we're not sharing this function elsewhere in the application of having this defined inside use effect is this function is not recreated or redefined every time the component renders it's only created this first time and called into action hey thank you guys so much for liking the video if it helped you get started with react also i appreciate you watching and subscribing it's helping my channel grow take care and i'll see you again very soon
Info
Channel: Dave Gray
Views: 2,634
Rating: undefined out of 5
Keywords: fetch data from api in react js, fetch data from api in react, fetch data from api in reactjs, learn reactjs, learn react js, learn react, fetch data, fetch api, fetch data from an api, fetch data from a rest api, fetch data from rest api, rest api, how to fetch data from rest api in react js, fetch data from an api in react.js hooks, fetch data form api in react js, how to fetch data, react data, react fetch, react async fetch, react, react tutorial, reactjs tutorial, js
Id: 9vvtO0S1KlY
Channel Id: undefined
Length: 23min 40sec (1420 seconds)
Published: Wed Jul 14 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.