Fetch API & Rendering Data with JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up everybody hunter here and today I wanted to take a look at using the fetch API from a browser and how we can fetch some data and then print it onto the screen using just vanilla JavaScript and here we go this is some documentation on the fetch API the mdn Doc's they're pretty helpful but I wanted to just show you how it works real quick one quick note is that the fetch API is built into the browser so let's take a look at the browser compatibilities here note that it will not work with Internet Explorer but you know Internet Explorer is on its way out but on the all the other modern browsers you can use the fetch API so if you don't need to use Internet Explorer you can use the fetch API alrighty what I have here is just a very very basic index.html and I have this examples or example j/s file which is here and all I have loading is a function that says fetch data and I'm calling that function below and we'll do all our stuff in this function and I have that open here and if we go to the console you can see we have the start fetched if I do a reload that console.log is here so everything is working and the API we're going to use is this request response I n site right here so it gives you some fake API endpoints to hit so you can get like a list of users you can like post to create a user we can look at post as well you can do that with the fetch API first let's get some users and let's display it on to the screen all right whoopsies here we go so to start we can just do fetch and then in fetch you want to give it the the URL that you're fetching so if we go to here and we're doing the users I think we click on this in the new tab okay so this is the data we're gonna get and let's just do this this one right here alright if we paste that into the fetch let's take a save okay let's go back here and do a reload so as you can see nothing happened in the console we take our look at the network tab we can see that it's working so let's do that again the reload okay so this is the fetch this is the URL we paste it in right and it's doing a get by default then we go to preview we can see that data is coming in cool so it's working before I go any further I wanted to just do a console log of this let's just see what's going on here so what is this actually returning to us all right what happens what what happens when this runs so if we go back to the console okay so we can see that it's a promise that is returned and there's like an initial pending status so I'm not gonna go into too much how promises work I assume that you have some promise experience if not let me know down below and I'll make your video our promises but knowing that this returns a promise we can now do something like this right you can chain a dot then to the promise and what this gives back is response okay and now I'm going to use an arrow function here and we can do a console.log a response and we can see what it looks like so we know it's a promise we change then okay so now this is what it actually looks like this is the first thing that gives us back so this is known as a response body so let me go back a little bit and then yeah this is a response object right and it has like a status right here and there's like it is okay here I'll go into this in a little bit but what you want to note is that this isn't very helpful to us in its current state so we need to do another step to this to make it a little more useful what we actually need to do is run this if we go back to here we need to run this JSON I guess they call it a body mixin so you can run this on the response to transform it into JSON and that is what we're gonna do so with promises you can do another then now actually let's do that in here let's do that in here real quick and see what happens so response dot JSON right so we can do a Const data equals response that JSON and let's do a console dot log of beta let's see what happens if we just tried to do that all in here okay we get another promise right so that means we need to wait a little bit for this - for this response that JSON promised to resolve before we can just use it immediately right so that means we need to do another then and in order to kind of wait for it you can run the response that JSON and then you can just return that so if you return it it's going to come into this second then once it's done and now we can help data in here another l function console dot log data now let's take a look at what data looks like and now if we do a refresh okay cool we see that it actually looks like something we can work with so this is the object that gives back we take a look at the network tab basically looks more like this and so now there's another data property on it what's the actual array of data that we want all right so what we have to do is now do the data dot data I mean you can kind of call this whatever you want like I think the docs just used this data example so you sometimes end up with data data it all depends on the API and the structure gives back this just happens to be data dot data if you find that confusing you can change this to anything you want so now if we do console dot log of data data give a low save we're gonna ignore all this stuff for now the pagination stuff and now we just have our array cool so the other thing we want to do is check for errors right so what you do to do how to do that is at the very end you add a dot catch and then any errors will pop up in here you can do a console dot log of the error all right cool so I want to show you a quick thing about this real quick about the fetch because if you see we try to type in a bunch of gibberish and try to throw this error right what happens here well we get a 404 but then we also get an undefined here right so as you can see it didn't go into this catch error it didn't actually throw any errors and that is kind of like I guess how fetch works it's not going to throw an error on certain things one of those things being a 404 so what you need to do is you need to check for it yourself basically you need to come in here let's do another console dot log of the response and see what that looks like do a little refresh okay so here's the response and then basically the status is 404 and you could do a check out all these statuses like if it's a 200 that means it's good but anything other than that means it's bad or you could use this okay which is a false so basically if there's anything wrong the OK is gonna be a false and you have to manually kind of catch that yourself so you can do right here is you'd be a little if response dot okay actually if it's not okay you want to do stuff Oh an error and you can make this the actual status or whatever I'm going to do air right here and let's take a look all right and I'm gonna leave this console dot log of the response up so we can take see what's happening okay so here's that console dot log and now we actually get an error here if we go to the example see how it's in the catch down like this code isn't running it's not trying to do this dot JSON that's what we want we don't want to do that when there is an error cool I just want to show you that because this is kind of an extra step some people kind of miss and then they're confused on when they get an error why their code still runs and then breaks the rest of everything so let's flip this guy back and leave this here and then we'll take a look at the response that okay again and so response that okay equals true that means we continue with our code and then here's our data again right everything looks good now get rid of this console dot log I'm going to leave this little check you're here and now let's print this to the screen so how do we do that well in the body with that some HTML maybe like a div or something then we can give it a ID no no I'll just call it like app or something right so we want to basically inject HTML 8 into this div using javascript well how do we do that we're gonna do in this step after we have our data so after everything's done we'll inject it and what you can do is do a document dot query selector right and then you do app and then there are kind of many ways to insert HTML into our into HTML with JavaScript one of the ways is just do inner HTML right and you can do equals I don't know if you just want to add a paragraph let's let's do it h1 we can just do hello so as you can see it works enter HTML works and you can just do maybe search JavaScript insert HTML I think there's a better way to do it okay there's another way called insert adjacent HTML which does pretty much the same thing but you can choose like do you want to do it before the element after the element it gives you a little more flexibility see how it there the example of your gonna insert it here or then insert it here or right before the tag ends or right after the tag and so this gives you a little more flexibility and so you do you to specify which position you want and then you give it the HTML that you want to insert all right so I think I might use this because it looks a little cooler and now we're gonna do I think we're gonna do after begin do it after that begins and then we'll just put the tag here see if that still works do a little refresher here cool the hello still there alright so we don't want just hello we want our data right so knowing that we have our data how can we kind of insert it so what we need to do is loop over the data cuz it's an array you can see here it's an array of objects so we want to loop over every object in the array and kind of construct a HTML string from it alright so this is what we're gonna do we're going to make a Const of HTML and that's gonna equal data data I'm gonna do a map over the array of data alright and what are these users so basically you can do user and you want to return and let's just return like a string here so maybe like the name right and you can do name so you could do like name plus like user dot let's take a look at what it says here so user dot first-name right that's one of the things on the object it could do name plus user dot first name right and we actually need a paragraph tag so you could use this plus the old-school way of doing the plus but we can also use the new-school way which is template literals and what those are is if you do little backticks here you can do you can just start typing in two here as if it were a string right makes it a lot easier so you do name and now if we want the first name you want to do dollar sign and couple curlies and you can just insert variables into here you can just insert JavaScript variables into here so you would do user dot first first name right so let's take a look at what that looks like real quick I'm going to leave this hello here for now I just want to see what where we're at so let's reload okay cool so as you can see now we have an array because map gives you back an array so now we have an array of name George so name alright this is certainly looks similar first name first name Janet Emma right everything looks like that but it's still in an array format which is not what we want we want it to give it to us in kind of a single string so to do that at the end of the map you can just chain on a join if you just join on the nothing like a blank then it will give you what we want okay cool so now this is what our HTML looks like we click on this um click on this example see how the HTML is here this is what we want cool now we can just put our HTML instead this hello we can put it here we'll do a save let's just delete this go quick actually I want to leave it and now we see the data praying to the screen right and if we inspector it undo the element you can see that our paragraphs I working cool let's add some more stuff to it now right because you can basically do whatever you want in here I mean it's a little weird writing the HTML like this but this is kind of how you need to do it when you map over the data so if you do like a div right and like a class maybe of user and you have first-name [Music] think email is another thing you can have email all right leave that and see what it looks like ok cool inspector here and we get the user div with the class of user right and then we have the name first and last name so let's style this up a little bit how do we style it well you go in here you can just add in a style tag and we can just target that user we that the user class on this dip that we did right so maybe we do something like user and we'll give it a background color now no light gray and then some padding and then maybe some margin at the bottom okay so now okay cool we can see that things are happening so we're now getting the data using the fetch API and then we're just putting on the screed it's something I like to do because when you're just in here looking at the data it sometimes it doesn't mean anything it's a little more exciting when you can get onto the screen and you can actually style it and stuff like that so I find that to be a lot more interesting in the examples so let's add one more thing which is the profile image right close tag all right so if we go back to our data there was a profile image on here okay an avatar right so we want this avatar which is looks like some s3 link so I should just work and what we want to do in here is the same template little twig little things so we'll do user avatar right and then for the alt tag let's just do use it at first name for accessibility reasons always want to put alt tag on your images so now when we reload cool we get images here we get the name and we get the email all right so that is how you use fetch kind of went a little off tangent with this mapping and the HTML stuff but you don't have to do this right you can totally skip this step if you want to this is weird to you you don't need to use your data like this you can totally skip that part but I just thought it was a little cool thing to add so the other way you can use fetch is if you do a post request so say you want to create a user right you can do something called a post request instead of a get request and that is based on this so if you want to create a user you want to do a post request and what you can do I'm just gonna copy this and I'm gonna do post data and I'm just going to leave this part may be able to leet all this stuff in here alright so now we're posting data everything looks the same so how do you post data well in fetch you can give it a second argument which are like options to fetch and if you go back to this close some of these you go back to this I think there's a options thing here under the fetch API there is it concepts and usage maybe I don't know there it's somewhere and these Doc's but one of the things you can do is you can specify the method and now we want post right and then another thing you want would you do this when you post you want to add in some headers you want the content type to be application that's JSON so this is like telling you telling the the API you're posting to some additional information so you're saying all right I'm gonna post to you some application dot JSON and then the apps little thing you're gonna post is gonna be in the body okay and you if you just try to do it like just an object it's not going to work so let's take a look at this example right so they have a name and leader as the post and then when you create it there a spot should give you back name leader and an ID right so if you just give it this it's actually not gonna work let's take a look at what happens so we get some errors here let's take a look at the network tab and this is our post and what does it say okay they request the payload you're sending to it looks like this object object thing so what we need to do is we can't just send a straight object we need to wrap this in a JSON dot stringify and then so it's going to turn this into a JSON object which we're telling the API like we're about to send the JSON object so when you make it into a JSON object or JSON string and now it's going to work so when you do the post the payload you can see looks like the one we gave it the post is here so if you're curious where those headers are the request headers is what you're sending so now you can see application JSON here there's some other ones here too and then on the preak on the response not a previewing response are basically the same thing preview is just like a prettier version you can see that we get the Morpheus leader back or the Morpheus name back leader job so that is working as well and one more quick thing or I'll show you is you can actually do something like this if you're on some like random website or you need to troubleshoot why your why your fetch isn't working you can kind of click on anything that is a in the network tab anything that is a request you can kind of right-click on it and do copy as fetch okay if you do copy as fetch come in here let me open the new file you pasted so this is actually going to copy for you the same exact request you're making right so you can kind of see what headers you're sending if you have to send along like credential tokens and stuff like that you can see what those look like and you can kind of use something like postman and you can put it in there to troubleshoot it or you can copy it and like take it into a brand-new HTML file and poke around on it so that is a nifty trick if you wanted to bring it into a postman you would probably do something like a copy as curl and in postman you can import that and it will give you the request if you ever use postman if not you can copy those fetch and tinker around with it so that is the fetch API kind of a general basic overview on how to use it hope you enjoy this video it's more of a vanilla JavaScript video if you like this video give me a like subscribe to my channel the other way to do the promises is to use async/await if you're into that I can I guess do a little gist of that if you want to see an async/await version let me know and I'll do that and I'll put it in the comments as well anyways have a great day
Info
Channel: Code Bushi
Views: 62,479
Rating: 4.8867579 out of 5
Keywords:
Id: FN_ffvw_ksE
Channel Id: undefined
Length: 28min 41sec (1721 seconds)
Published: Sat Dec 21 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.