Fetch API with Async/Await (GET, POST, PUT, DELETE)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone in this video we will look at how to upgrade your fetch calls to use the async await syntax this is the modern syntax to deal with asynchronous code and is preferred by many people so it's important that you understand how it works to understand that we have to look at the traditional syntax first so i have opened a project here it's only one button on the page and i've also opened the console so when i click on the button we want to get users in this example so the button here was just a button in the html right so we can select that right here right so let me very quickly do this right i like to append l to the variable name to indicate that a html element is stored in there and then we're going to attach an event listener right so here we want to listen for the click event and when that event occurs we want to run a function called click handler which i'm going to create right here right so this function will run when the click event on that button occurs let's quickly check this i'm gonna save here i have live reload so now when i click on the button we see two in the console alright so let's try getting data from a remote server so we can use fetch for this right fetch and we only have to specify the address actually for a get request we're going to use a service called reqrest.in this will give us some fake data so usually with external apis there is the word api in the url and then the name of the the resource that you're interested in in this case it's going to be the user's resource all right so this is all we need to make a so-called get request let's see what we get so when i now click we get a so-called promise now i have a whole video on promises i recommend that you watch that after this one we can create promises and we can consume promises and the vast majority of the time we only have to consume promises so here we also only have to consume the promise right so fetch here is basically giving us a promise right so you can imagine promise and we can consume a promise in two ways we can tack on.then this is the traditional syntax and these days we can also write a weight in front of the promise right so let's continue with the traditional syntax first right so we can tag on.then and usually it's uh formatted like this right so eventually the server will send back a response and we get access to that in here we can call that response or just res let's see what we got right so now when i click on this we get a response object so what's important here is we see the http status code which is 200 so everything in the 200 range is good if the http status code is in the 200 range the ok property here will be true otherwise it will be false and then we also have our body and this will actually be the data that we're interested in but it's a it's something with a stream but what happens here is actually that we don't get all of the data initially because you can imagine we could have a lot of data right so all the data still has to be streamed in here so what we're going to use here is rest.json so with this method we're going to wait until all the data has been streamed in and then it will immediately parse the data as json because the format that the data will be in will be json format we cannot work with json in our javascript here so we need to convert it from json to normal javascript right now since we have to wait some additional time until all the data has been streamed in this method will also give us a promise and we want to return the promise you can tag on another.then right so it's a little bit tricky to understand how these then uh blocks work that's one of the reasons why async await is generally preferred but this is also typically formatted like this so then in here we finally get the full data right that has been completely downloaded and parsed as json so let's log this to see what we get okay so now if i click on this we get the full data so this is all of the data now usually we're not interested in everything right so i'm not interested in total pages or per page i'm interested in the actual users and they actually also call it data so then in here we we see all the data right all the users we have to drill down a little bit here let's actually try logging one of the users names right so i'm gonna say user at index three and we can say first name right we should get eve here so now if i save here and i click on the button we get eve all right now very quickly about error handling in the traditional format two things can go wrong for example when we make the the get call our internet falls out there's a network issue in that case the promise will be the promise from fetch here will be rejected and we can deal with that in a catch block so we can say dot catch right now in the real world we may want to show an error component or you know output a message here we're just going to log it right so a network issue means that the request response cycle cannot be completed so then the promise will be rejected here now another thing that can go wrong is for example if we try to access a resource that does not exist right so in that case the server will send a response to us you know with a 404 error right in that case the the request response cycle is still completed right it's just that the server is letting us know hey this resource does not exist so we can deal with that typically like this now if the okay property right remember that one if that is not okay well we can do something with an error component here we'll just say problem and then we also want to stop the function here we do not want to continue here if there is a 404 error or maybe a 500 that has got error right so 500 is what we get if there is simply you know a generic error on the server right so in that case the ok property will be false and we go in here and we return here if you have a return keyword it will stop the function if the ok property is true meaning the http status code is in the 200 range we continue here so this is also called a guard clause okay so this is the dot then syntax and there is nothing you know necessarily wrong with this it's just that it's a bit difficult to understand how these delta den blocks actually work and also if you have multiple fetch calls after each other things tend to get messy very quickly so we now have new syntax i'm going to comment this out so you can see the traditional compared with the new syntax which is going to be async await now async awaits works the exact same it's going to do the same thing it's just that it's a different syntax right so people also call this same tactical sugar right so we will still have fetch right so fetch stays the same here right and the url also stays the same so remember fetch gives us a promise right so what we get here is basically promise and we can consume a promise in two ways so the traditional way is then that's what we did here right but you can also write a weight in front of a promise right so now we're gonna consume the promise by using a weight right and if you use a weight you have to make this an async function right so basically you just have to write async here right so now we're using async await to consume the promise right so we're still working with promises this is a mistake i often see people think that we replace promises and this is not the case right so fetch still returns a promise it's just a different way of consuming it basically it's a different syntax but we do the exact same right so make sure you check out my video on promises after this one okay so what do we get from this initial fetch call well previously here eventually we got a response right let's ignore the error handling for now but eventually we get some kind of response and it's the same here right so eventually this promise will be resolved right so we can store the result of that well in a variable called rest right same as here and if you remember this response well the initial response object does not have to complete body data yet right it can take some additional time before we have all of that streamed in and also we want to parse that as json right so here we used rest.json right so we can do the same here actually now since we have to wait some additional time this is also asynchronous god right so we actually also get a promise here right so you can imagine promise now we can say oh wait we can in front of a promise right so we can do the same here we can say oh wait and the result of this will be data right so just like here right and what do we want to do with the data well let's just try logging the same thing and let's see if we get eve again i'm going to log this right so data.data index three first name so now if i save this we should get the same result in the console and indeed we see eve again right but now we're using async awaits all right then very quickly how do we deal with errors in this case what if there is a network issue which will cause the promise here to reject well we also have a try catch statement in javascript and this is its own thing but people typically use this in conjunction with async await so here in if you put code in a try block if a promise is rejected we go in the catch block here right so it's very similar to dot catch right so let's just do the same thing here okay and then the second thing is when the request response cycle is still completed but for example we try to get a resource that does not exist right so you get a 404 error or maybe something else went wrong on the server and we get a 500 status cut error right so in that case the ok property on the response objects will be files right so what we could do is this if the ok property is false we you know you can output a message on the page but here we'll just log something and then we could return here now you could write it like this but what people typically do more often is they actually put it after data and let me actually add some space here as well right so now if you write it in this sequence we are still going to parse the response as json even if the ok property is not true right because we're only checking for that here and the reason for this is you know let's say we get a 404 error the server will still send back a response and usually that response is going to have like a message like a description of what's the problem right right and that should still be in json format we also want to parse the response body data as json right in that case right so in both cases when everything goes right and when something is wrong we still want to parse the body data like this right so then here if the ok property is false you know maybe the server has sent back a description right so we can say data.description right so this is actually a little bit better and this is easier to do here with this syntax than with then here in dot then add another reason for using async await okay so i'm going to remove this here and i'm going to put it side by side so you can pause the video if you want to study that for a little bit longer okay so this was for a get request so very quickly how does this work for a post request right so let's say we have a new user let's say we want to submit this user to the server right so then the button should be submit user right and if we want to submit data we cannot use a get request we should use a post request right so it stays the exact same but we have to add an additional argument here an object with some options so here the method the http method the default is get right so we don't have to specify that if you want to make a get request because that's the default but here we want to we want to make it a post request we want to add something to this resource right and since we're going to submit data we also need to let the server know what the format of the data will be and we do this with headers so here we have to specify one header the content type and it's going to be in json format which is in the application category now you cannot write an object key with a hyphen like this so people typically wrap this in quotation marks and then after headers the actual data in the body that we want to submit right so this is new user this isn't javascript object right but remember the the format that computers use to exchange data is json right so we should convert this to json format right we can do that with json.stringify okay so this is how we can submit data now one other thing we should change here is well the server may send back a response right like a success message right so let's see here we are not getting this data again right so with the get request we got this data but now we're just gonna get something else right so we're not really interested in what the server sends back in this case but whatever it will be let's just log that here right and if something goes wrong well the server will will still send back a message with you know a description or at least that's what the server should do right so this is an example of how you could do it with post so let's actually try that i'm not sure if this surface actually uh works like that okay so they actually do work like that and they actually send back the the object that you submitted right and they even add an id and a created ad property right so this works okay so that's a post request how about a put request so with put we want to update or replace one particular resource right or sub resource right so users is the resource here but we have to specify which particular user right so usually you have to add something for example the user with id 33 right so this is the the serp resource that we want to update or replace so when you send a put request then the server will understand that the that the goal here is to replace this user with the new data that we're sending here right new user and i think this service here does not uh has not implemented this right so this this is an example of put and then delete is a little bit easier so with delete we still have to specify which particular resource sub resource we want to delete but now we're not going to send data right we want to delete data so we can remove the headers and the body here right so we don't need this anymore either right so this would be a delete request with async await all right let me quickly change this back to the get request yeah so this is the the get request now there's a lot to improve here we can make this much more sophisticated and professional and that's something that you will learn by going through my professional javascript course in which we will build two beautiful real world projects from scratch step by step so check that out if you're interested in any case thanks for watching hope it was helpful and i recommend that you continue with the promises video
Info
Channel: ByteGrad
Views: 21,689
Rating: undefined out of 5
Keywords: fetch api async await, async/await, async await, js async/await, js async await, fetch(), fetch api, fetch() async await, fetch() async/await, fetch async await, fetch await, javascript fetch api async-await, async-await, async js tutorial, fetch promise, async await javascript, web development, programming, fetch api tutorial, async await tutorial, fetch crash course, async await crash course, fetch promises vs async await, promises or async await, promises vs async/await
Id: 3yi0yvHgPfQ
Channel Id: undefined
Length: 14min 54sec (894 seconds)
Published: Thu Jul 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.