Fetching API Data in React with TypeScript - Async/Await, Axios, and Promises Explained!!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello fellow Learners are you excited to dive into the world of react and typescript then please subscribe to this channel because I will be creating some exciting projects in react with typescript yes with typescript because I have searched through the YouTube and I have noticed there are thousands of projects in react yes and hardly any projects available using react uh with typescript right so I would really appreciate if you hit that subscribe button and stay up to date for new project yes this is a new channel but I will really appreciate your support and your sub will motivate me to keep on creating new projects every week so let's go ahead and see what I have got for you in this tutorial so what are we gonna do in this beginner friendly video we will learn how to fetch data from an open source API and display it on our web page right don't worry if you are new to coding I will be your trusty guide every step of the way together we will uncover the magic of Target strong typing and create this simple application which fetches the holidays from a 2020 calendar which is available on this open source uh API so if I click on this one there are many API we can just change whatever we want but for this one I picked this one and it has date it has local name they uh name and country code what I'm doing here is I've I'm fetching the country code here I'm getting the date and I'm getting the holiday and I'll show you how to do that and so what are we gonna do how to fetch the API data in react using the typescript how to display the faster to the user and how many different ways are there to fetch API that are in react.js we will be doing three different ways there are many different ways to fetch the data as you can see I've listed eight here but mainly we will be focusing on fetch API and axios the other one get a little bit complicated maybe in the future I will cover them up but for now we're gonna use fetch API axios which is a third party library to make HTTP request we will dive into that when we start coding so let's go ahead and as you can see this example I have created using the code sandbox which is uh which is an online IDE for react and you can use it for other projects as well but I like using it because I do not have to install a react app every time I have to create a tutorial uh in this case when you're using the code sandbox it comes pre-installed but but don't worry I will be using vs code and we will install the react app from scratch and then we will create this right so let's go ahead and create this so I have my vs code open here and inside my vs code how we usually install a react app is npx most of you already know this who watching this video but if you are a beginner npx create Dash react cash app this is how you create a react app if you press enter it will install the react app with JavaScript right so it will be react.js app but we are doing typescript so you can do test Dash template actually you gotta name your app here so create npx create react app and your app name so sorry about that I'll I'll rushing it too much so what you want to name your app you can name it whatever you want but make sure you you following the naming convention here because you cannot use the camel case here while naming your react app fetch you cannot do this API data right so you have to use fetch let's use underscore API data so if you press enter this will install our react app with JavaScript but we want JavaScript we can use dash dash template type script and you can press enter all right now that the app has been installed we can do is it's the tab itself tells you that you have to go to that project because mostly what we do is we just go and PM start here and then we get this error because we are not into the directory right so we have to go to let's say where we have go inside this folder we have got this this is our project file so we're gonna go CD change directory to fetch API data now we are inside that directory over here you can do npm start or if I'm I'm using yarn so I would do yarn start but if you're using npm you can do npm star and hit that npm star it will start the app so that's that's the pretty Basics default app we have got here now we want to get rid of this stuff what we want is a clean app I always do this uh this warning I don't know why I get this warning in my Mac but it goes away if I start the app again so I'm gonna do that it's nothing really related to the project so this is fine and now we're gonna go inside our project folder we're gonna go to source this is how the react typescript project looks like right instead of JS you have TS and you have TSX file which is your functional components and you can see you have your TS file this is your configs file and this is the main important thing that it does add using the template typescript which is this config file so you can see this one this is the config file right but let's go ahead and remove the extra stuff that we don't need we don't need app.css we don't need index.css we're gonna do our custom style so we don't need this logo we don't need this so we don't need any of these let's delete that delete that delete that all we're gonna keep inside this oh did I delete index.tsx [Music] you cannot delete index.tsx so we're going to delete this [Music] logo we don't need react app we don't need to react web settle we don't need this file we don't need CSS file and we don't need this file we do need TSX file so we cannot delete that I don't know why my apps no select I have to delete them one by one so here you go so we just need these two files in here and then we have to remove the stuff that these files are importing which we deleted we deleted index.css we deleted this always try to complete clean up your app when you're using the template typescript or npx create react app it's gonna screen for logo here and let's get rid of everything inside this we don't have any class buddy so get rid of that now we go into our public folder here we don't need favicon I mean if you do want to keep it you can keep it and replace with your own fabricone we don't need logo we don't need manifest we just need an index.html file and inside this we're gonna clear up some stuff [Music] you guys can always skip this because I make videos for beginners as well if you already know this stuff just you can skip this I will add the timestamp so you can just go to the fetching part or creating the component part so I am gonna do this this is clear we don't using favicon remove that now let's go ahead and create a folder inside our source always create this folder right this is the convention components because what we do in react we just work with components and inside this component I'm gonna create a new file which I'm going to call us holidays Dot if you're using JavaScript you would do this or something jsx but we are in typescript so we use TSX and this is streaming because I do not have any functional component inside this is asking for it so let's go ahead I use this snippet code react Arrow function component export this snippet is called actually this extension is called react snippet so like in my previous video I always try to tell people if you want to add it you can add it it's called The react snippet so install this these are shortcuts for react but we have that so what what this snippet does is react Arrow function component export right you get this component and now there shouldn't be any error app.css in Edge applicator okay so we don't have app.css I'm still calling it somewhere there it is now the app is clean now you can do the magic here so in this component why did I create this uh us holidays component this is the component that will be responsible for rendering the API data right so in this component we are gonna leave this one for now because we will display the information in a table and so first thing first let's go get the API link so it's actually on this website it's called mixed analytics what I did is I just typed free API link for testing on Google and then it was at somewhere here big list of free and open apis if I open this I get this us calendar this is the link you click on it all you need is copy this link from here and now we can actually have a file inside source we can call it API [Music] links dot TS and we can export it from here export most API link and you can copy your file here now we don't have to use this everywhere we can just simply use this variable over there [Music] if you go to U.S holidays and let's actually test if it's working so we give it a H1 tag hello I am us holy days and it's called this component inside our app because our app is responsible for rendering everything us holidays where is my react app hello I'm useful so this is working perfectly fine [Music] now first thing first what we want to do is we're gonna create a use State variable because the data that comes from the API we want to store that in a variable right in a used State variable so const I'll probably name it API data or you can name it whatever you want API API data and then a function that set the state to this variable so set API data react Dot ease state and this will be just empty let's go ahead and create the first function which will be the fetch API right so fetch API we will use fetch API using fetch API you can use async await and you can use the promises so first thing first we're going to learn how to use async await right so when we're using the fetch method so this is something called Fetch which is a built-in JavaScript function right it's built into the browser what it does is the fetch API is built into modern browser and it provides a simple way to make HTTP request it returns a promise and allow you to handle the response using the dot 10 and Dot catch right and also using the async await don't worry I will explain you both uh when we do this so first now that what now you may be thinking like what do I mean by door 10 and Dot case right like I said I will explain it to you don't worry my friend I'm not going to jump into coding part without even explaining the definition of this to you I want you to understand that what exactly happening when you are writing a function which fetches the API data right so when we fetch methods we use the fetch method remember both async await and Dot 10 are different ways of handling promises in JavaScript right okay now what do I mean by promises you may be thinking it's saying promise what do I mean by promises promises in JavaScript or typescript it's the same thing are a way to handle asynchronous operation and manage the flow of data in more organized organizable and readable manner they represent a value that may not be available immediately but will be resolved at some point right so when we are sending a request there's the servers take some time right so it the asynchronous function does what it does is wait for that server response and then display to the user so then we get the information and we can use it right okay so that's the definition of promises and we will see how we can use both of both of them to fetch the data in our example right now let's go ahead and try to fetch some data from an open source API which I already created another variable and we will use the async away method so we're gonna go ahead and create a function which will fetch the data from the API so let's name it data API and yeah of course it will be an error function everybody uses error functional so this is how you create a function simple right everybody knows it inside this function what are we going to do we're gonna use async await so I'm going to comb it out it here fetching actually make my comment much better with this fetching the API data using using async oh wait right so inside this function how do we use async await you have to write it here is sync and then you have to use try what is this I will explain it to you don't worry so let's let me just minimize my terminal [Music] so we go try inside try we're gonna create a variable which you will get the response and it's going to await that response then we use the fetch method so this is the fetch method which then does what then take the our API Link in this case which is this you can either copy this here as it is [Music] like this or you can just import this and then just put this value to this so let's try that import API link from there and rather than doing that we can just pass it the API link this is much cleaner way of doing it and now we have got that response what we're going to do is get the response and stored into another variable data and which is also awaits thieves response as Json format right so once we have got that now we're gonna use this function to store the data that's coming from the API so what is happening I'm making a request to this function I mean this API link using the Fetch and then when that's being the data is being loaded to this variable the data is being stored into response as a Json format and then it's getting stored into this variable then what are we going to do we're gonna do set API data to data right so now these functions have this data in in it right so this is passing it to this this is passing you to that and this is passing it to this now this variable is this variable can access all the data from the API right how do we know that we can console uh console.log and we can check the data that if data has data the API that I mean and now that we have done that we need to catch the error we have used the try we need to cast here so we can catch [Music] error and we can console console of the error using the error console.error and we can say that no data found or you can say actually just always keep in mind with as a front-end developer when you're doing this kind of stuff think of the user perspective as well they don't know what does it mean no data found or what so just write something like oh something went wrong wrong please please try again and then pass your error here so that's it this is how you fetching the data this is the first function that fetches the data but in react this is not enough we have to pass it a use effect hook so we go react dot use effect and inside this we're gonna fast this fetch.ipa function and with an empty dependencies so now this variables holds everything that coming from this API link so which what do I mean by that this data is now available [Music] on this link right I already did a console log here let's go ahead and look if that's working we go ahead and we go this there we go we got data here we got date just like this this whole data is now inside our app that's how you can test whether your data is working there's another application that I call Postman you can also use that to actually check if your apis so we know that our API link is working we got it as a console we don't want to use it here and one more thing if let's say if something is wrong with the API link right let's change the link [Music] and okay something went wrong please try again error so this is the error state that the catch is catching this error right Ctrl Z that now that we have data what are we gonna do inside our return that's where we actually do our HTML which is not HTML it's jsx inside this we're gonna actually rename this div next thing what we should do is because I don't use CSS I use style components so I'm gonna go ahead and install the style component so I'm going to npm I styled component so this shouldn't take that long while that's happening we can let's check package.json we have got styled components yes we go style components hide the terminal and now let's import styled from style component I'm gonna create a custom style component here const ant holy days wrapper equal to style which we imported from style component and when you do this dot div so what I want to do is I want to pass this over here and then what I want to tell style component that I wanna style dot I wanna treat it treat this as a div so if this they will be removed from here and then this will be used I want to trade if you want to use Like A P tag you can change this div to p then use the Templar literals now that's perfectly fine so now we can do our styling inside this whatever inside this this wrapper we can style it here so what are we going to do we want to create a table first so like I said I am also fetching this from the API so let's go ahead and declare that first and I will show you why I need typescript as well [Music] okay I imported at the wrong place so inside this what are we gonna do is we're gonna go ahead and call that variable which holds the data API data and API data it is checking if it's not null dot length actually let's see if this has access to anything api.org can we just display pie data like this no you cannot because we haven't declared the types for this so what are we gonna do is we gonna console off this again log to check the data please date look at this needs to be removed [Music] so we're gonna have a look at it what type of data are we expecting so we are expecting Aries we have got area elements here you can see that this is an area which holds the objects inside it and to do that we're gonna have to declare the types for this right so we are expecting we are fetching the country region date and holidays so which is the country code and a date looks like this is a string this is inside a quotation mark this is also string name is also string so basically all three are things that we are fetching their type would be string so now let's do the typescript so all on top of your component you can create an interface you can name it whatever you want I'll name it API props and inside this what do I want to fetch I want to fetch the name of the country which is I mean not the country the holiday what's the name of the holiday let's go ahead and do name and what is it it's a string obviously and date it's also string now what's the other one country code make sure this matches exactly what you're expecting from the database so string [Music] now we're gonna pass these props to this use State because this is what this variable is expecting these three things and then after passing that we have to pass it as an array element because this is an array so now we have done that we can try to fetch the information here now if because we were getting arrows before now we try to do that in the jsx again whatever is in your return statement is called GSX in react so let's go ahead and do API Tara and so we're checking if it's not null API data NDP data dot length is more than zero then what we want to do is [Music] inside this we are going to create an H2 tag which will be the title public holidays for what public holidays for API data element zero dot country code there we go we go public holidays U.S I never wrote U.S you can see that I have never wrote you guys I only wrote public holidays now this country code is coming from the apis right where is it coming from it's coming from this array this this is getting rendered here let's wrap that up and now we have the title what are we gonna do is we're gonna create a table right so I think we need a table to display the information so we'll come here we'll do a table we'll create a clear head which is tables head and inside this we will do table row um I'm assuming that you already know how to do Tables by now right th which would be the date the second is holiday what is it the second one holiday type I'll just say already type what type of holiday is this and once that's done table head is done we connect to table body here what we're gonna do is we're gonna map this function so you know how we use Loops we use map function so we're gonna map everything so we can fetch all the data here so we're gonna since this API variable has access this API that I have access to everything so we're gonna again check if this data is not null API data dot map and then you can say name it data or you can name it whatever you want because then this object attribute will have access to everything inside the API data right and I'm gonna do index why I'm doing Index this is a key Pro because whenever you're mapping something you need a key prop as well so we've got that now inside this we're gonna go table row we're gonna pass it to Key prop which is index Mega Boolean is not a cyber perimeter API Pros index number arrays reactor node okay I am getting a warning here API data and the period map is this let me try create this first and I'll figure that error so cable data would be [Music] data Dot nope [Music] let's name it something else info [Music] or items inside that okay I'm not having access to that one I think my math function isn't right API data what we can do is you can [Music] let me just write this whole thing again because this is where the confusion is happening we're gonna get the API data and we gonna check if it's no no and [Music] API data then gonna map we're gonna name this it will be index index is the key there you go I knew that something was wrong and it was a syntax error told me about it TR key in index I'm providing this key to this and table rule then gonna have table data now the info will hold when you go in for DOT see it has information to this so the first one is there we're gonna put date there the second one is the name now let's go ahead and see what we got there there we go uh let me just remove this because we don't need any more information so we can remove that console always remove your console logs and never forget them hold on to manifest why I'm getting manifest warning here I don't even have manifests somewhere maybe in index and there it is this is the one that's just bothering me for no reason now it's clean always try to keep your console clear as well so now we have got the data you can see that we're fetching we just need to style the table as you can see it wasn't that hard we just did three things and then we just created a function excuse me we created this fetch function via this fetch function we pass this the API information to this state which is here this is storing it here and then all we did is just created the interface for typescript and here we pass that props to this use state it depends if it's an array element sometimes it's not then you don't have to do this and then which is fetching the information using the map function so that done now we have table body here which is finishing table is finishing so now let's go ahead and style this to make it look better like you know how it's looking now right right now it's just looking like the basic um really default table that you get but we're going to style it or something like this so how to do that we go to our wrapper in our style components you can style your H1 inside this what you're going to give it March in top maybe two Ram two Rams is 32 pixels I need to be on here I want to see if this is actually applying okay it's H2 or H2 now that's moving the next thing we want to do is we gonna get the table and we're gonna give it a border border collapse where's the water collapse property there's water collapse we want it to collapse no and we're gonna give some margin inside the actually we're gonna move this table to Center so what I'm gonna do is I'm gonna give it marks in order so now this is in Center okay looks like my H1 is outside that uh that shouldn't really matter because that should be inside the table even if it's outside the table so that's just moving the table to the center right so I have to text align that to Center as well there it is margin we give it a margin now we're gonna get the table heading what are we gonna do we're gonna give it a background color which is a hex code F2 F2 F2 so it's kind of grayish color you can see that one so small yet let me just we'll have to make the font size bigger as well for this whole thing let's try to make the font size to them that's quite big 1.5 yep so once we have the background color on that we'll give it a border to stand up on Pixel uh solid red let's give it what else we can give it we can give it some padding so it has some space inside its pixels there it is and we're gonna give it some width [Music] so now we'll cover up the entire screen so with that we'll see now this we need to align this into the center of it now we get the TD which is the table data we give it a border uh uh water radius of same I guess will be the same as this [Music] can we text align this to the center yes we can here it is [Music] we have some padding in here [Music] we might need to add some padding to the table that I as well [Music] boom okay that looks better let's see if we can make it bit smaller okay looks like the width is 100 percent now why I'm making tables uh table headings with hundred percent so make the table with hundred percent so it is a little bit responsive as well yeah so we've got that we've got that right that one is a bit smaller because of the size the font size let's do this [Music] and so in the width is smaller here but that doesn't really matter we have got what we wanted we don't want a red color on that we don't want a water radius of red of the th not the yeah this we want the power radius of this to be DDD DDD Grease so here we have that now we know how we can fetch the information what actually happened in this fetch function I will explain it to you right now right so now we have this uh API here you can see that in America I don't know it's an American Standard so first month and this is happy news obviously 2020 and then we have Christmas on 25. there you go you can see that and one more thing I wanna mention is I if you want to change the date you know like how the date is actually in American Standard but we don't live in the US so we want to change it right so what we can do is we can create another function here function to change the date format format right let's go ahead create the function let's say get format let's just name it change date format right and inside this it's gonna take the attribute as date what is string now you have to provide a type which is gonna be a string or number because it could be a string or number date could be a string or number right we're going to have like month as a string which will be January and the other day it will be as number and it could be date itself date itself is an object which is a date object [Music] and inside this we're going to create an object should be options you can name it whatever you want what do we want the ear to be displaced as numeric we want the month to be displayed at text so this is short a would also be the numeric version [Music] and [Music] after this we go as I International int l dot date format options [Music] now we create another variable here which will store the date and date object is taking the date string [Music] oh this should be new keyword [Music] now this function will return date to local string and we want it in the UK style so we go English UK and you pass the options to this give me this [Music] okay now this function can change the date let's copy this function where we are displaying the date remember now look at the date now 2020 one one right now let's go ahead inside this we pass this function inside this function will pass the info dot date what do you mean ah my bad actually we're not passing it as an uh object which is just date there you go one January 2020 isn't that much better 25th May 2020 but by default the date will be displayed in the American Center so now let's go ahead and see what is actually happening with this fetch function that's fetching the information from the data make it a bit smaller [Music] like this so this is the function right what is happening in there what is this async keyword is doing the async keyword is used to define an ins asynchronous function right this means that the function will return a promise implicit implicity and you can use a weight inside the function to wait for a synchronous operation to be completed let me skip my brush [Music] so this async what is it doing it's defining as an unsynchronized function right and what is this a weight is doing the await keyword is used inside this async function right to wait for a promise to be resolved when you use a weight before a promise it will pause the execution of the function until the promise is fulfilled or rejected So based on this await the execution of this function has been paused until we get anything from this API link right the fetch what is the fetch doing here the fetch function is a built-in browser API just like I said before it used to make the HTTP request in this case it is using just to pass that link here right and then we have response dot Json so what is happening in this way this method is a built-in method dot Json which is a built-in method of the response object that returned by the fetch function it pass the response body as a Json and returns a promise that resolved to the Past Json data right now what the set API is doing this set API is basically it's a state function that we have declared up here in our use state right and it is what is it doing is sets the fetch data now that we stored the response in data variable it says that fetch data to this and then this gets passed to this so what is happening this data is being passed to this and then this is passing it to to this API data I mean I couldn't reach it but this is the one right and then what are we doing this holds everything from the database we're using it down there to fetch the information so API data so that it can be used anywhere in our application right and now we have this understand this try and catch because the everything is wrapped inside this try and catch the try block contains the code this try block let me just mark it for you this try block contains the code that may throw an error right because we don't know if the link is working this API link is working or something wrong in the API call hey because we are actually making a request to somewhere else right if we don't have this in our server we don't have this in our database so in this case it is the asynchronized code that fetches the data and process the response right if any error occurs here during the process of this process it will be caught in the catch block and we have this block which is actually after this so what is happening inside the cat if an error occurs in the try block the execution jumped to the cache so nothing will happen here if there's an error with the API call nothing will happen here this data won't get to the set this won't reach up to here we will have an error and then where the error is caught and handled in this case the error message is logged to the console there it is and in summary what is happening is this whole function this whole fetch data API function is a asynchronous function that fetches data from the provided URL which we have here which is in our URL file and what it does is this function fetches the data from the URL and pass the Json response and set the phase data to some variable or state if any error occurs during the process it will be logged to the console so that's what you're doing so I'm gonna hide my paintbrush so now you know that right now what we're gonna do is we're gonna go ahead and use the axios like I said I will be using three methods so I'm going to wrap it up to not to make the video longer but we have used the fetch function here let me make it a little bit more standard comments so I'm gonna comment out everything inside this now we're gonna get error no data is here because we have removed the function that's actually fetching the data what we're gonna do is now we're gonna use axios how to do axios excuse is a third party Library we have to install it obviously so npmix use I stands for install it will be installed quickly check always check your package.json file whether this has been installed or not there it is X uses here hide the terminal hide the false now let's go ahead and do it the axial switch so again same function I'm Gonna Keep the name as same so I don't have to change it like over here in many of the places where I'm using this function cons fetch API data which is an arrow function and inside this function now we're going to get axios or X actually I have an import rate my intellisense would have imported it but I want to show it to you as well so import you import xeos from axios that's it foreign don't worry we will just use it right now so where is my XCS function let me just comment it as well fetching the API data using the using the X here axios dot What DOT get dot get what your API link or your API link directly goes in here because in this case I have the variable what is API use dot I mean the excuse Dot 10. and then get a response just like this function we get a response and what what happened with that response we can set the response response we can directly set the response uh we can store the response in a variable or we can get that response in uh another or directly to the set API data State function what we can do is response dot data why am I getting error implicit as any type what type of views okay it's asking me for the API props undefined [Music] oh my bad [Music] we don't have to do that I was like that's not the case here typescript wouldn't react onto response because I was importing it without the quotation marks so we have got that now so we got response dot data so what you could do you could do it this way or you could just do the same approach that we did here you can get this response before we got it as Json but now we're gonna get it as Tara I'm gonna use a weight here so now that response dot data is getting stored into Data and then we can use the set API data to data and with that it should work well it is already working but we are not catching the error now again we're gonna use the dot catch inside in this case it's dot catch so let's pass it the error not importing the error error you get outside of this you do this and then you just console cons console dot error We're Not Gonna log use console.log here but we're gonna again provide something to the user something went wrong again this not keep it in the console you can store it in a state and show it to the user which is error so that's it this is how you use axios and let's check the console pretty clean yep let's see if the catch is working if you change the API link [Music] there you go something went wrong right because there's something wrong with the exit always try to use the cache blocks so you know that you know getting something from the API and you can see the API data is not being fetched and this table is empty let's undo that come back to here we're getting that so this is how you do a the X Series this is how you use axios now have a look at this I'll get the brush [Music] so what is happening inside this this is the fetch API data function right this is a regular synchronous function this is not an insulin asynchronous function one like in the previous example xeos uses promises for handling asynchronous operation so it doesn't require the async of weight right it doesn't really need the async await function because it's using the dot 10 which are the promises so what is happening with xus DOT get [Music] pretty simple it's just provide an API for making HTTP get request right in this case the access get method is used to fetch the data from this URL that we have and what is dot 10 doing so dot then method is used to handle the successful response so if you get a successful response then what do we want to do so if we get a response successful then it takes this callback function right that will execute one the data is successfully fetched right and then what is response tortara is doing axios Raptor server responds in an object and the actual response data is available under the data property so we have to access it under the data property and here the First Data is stored in this variable right I mean we stored it inside this data variable it's like confusing with naming I should change the name of the variable that I'm fetching so let's change this to fetched okay fetched Dara and then we pass that to this fetch star it should still be working here now get the brush again and what's the next thing again once you have the festara inside this variable it's again setting it to this state function which is storing it into this which is getting storing into the uh your use date variable up there I cannot scroll with this let me just hide this so I can show you inside this so now this variable holds everything from this data using the axios right moving on to the next one which is the catch again same thing again the catch method again used to handle the errors so the errors that might occur during the HTTP request or processing of the response then use this callback and then we'll console.log will print the error to this so in summary the faster API function using axios to fetch data from the provided url url there could be any URL you're working with and then set the Fest data to API data and if any error occurs during the process it will be caught in the catch block [Music] and an error message will be displayed so that's how you use axios right that's it so we have learned the Fetch async and the axios let's comment this out what's the next one we will not do is the promises so we will see that using the promises I'll copy this here fetching the API that are using the promises so this is the last one let's try to finish this one quickly so the video doesn't get too long and again inside this what do we do same function fetch I'm gonna name it the exactly same fetch API data Arrow function it takes the fetch method as well and you pass your API link to that and then what it does it does this it does I'll just write in one line dot 10 right then it takes the Callback function response which does what which then check if the response [Music] response dot ok if the response is not okay what do you mean by okay so the response object has an okay property right this property that indicates whether HTTP response status is the range of 209 and 2 200 to 299. so so this is gonna check this okay is checking if the range is 200 to up uh it goes up to two nine nine what does that mean so this is just a convention that they have set up so what does this mean basically is it's gonna check if it's matching there's numbers any numbers between 200 to 299 which means successful if the response status is not in that range it means there was an error and we threw a new error object with a custom error message right so what are we gonna do we're gonna throw a new error through new error with a custom message so no response from the server now once that what else if it's successful what are we gonna do we're gonna return what we're gonna return response as Json [Music] that's it and then we have another then in this case so let's just do this right so because my then he's up here we wouldn't know so this then is checking this and then after the return what we're gonna do we're gonna have another 10 then what then it's gonna get the data and we're gonna do what are we gonna do we're gonna set up the data uh to what just like we did before set API data to data like I said I should change this name to something else and this should be a closed okay my bad this shouldn't be here so once we throw the error we have a return which will return the response Json [Music] and then we have dot then we don't do then inside this it will be after this so then and we take another call back again I'm gonna rename it fetched [Music] Tara set API data to fetched and then we're gonna do this what happened after this we use the dot catch which takes another Colbert function which is going to lock the error console console dot error no data found [Music] and that's done we don't really need this here oops so we have done first link response just checking let's go ahead and see if it's working voila there it is now the promise is working nothing in the console.log everything is working fine so let's go ahead and talk about this function what is happening in here this whole function [Music] so we are starting with the fetch act the fetch function is a built-in browser again I've said that many times it is just using here the fetch function uh to pass the API link right and then the then is used for what [Music] the then method is used as an object here right so it is used in object and OK property that indicates whether the HTTP response status is in the range of 200 and 299 like I said if it's in in the range then it will be successful but we are checking if it's not in that range with this condition here then it should throw the error so when the response there is not in successfully the throw statement is used to create and throw a new error object this will immediately what we'll do is this condition what will this condition do is immediately stop the execution of the current and Dot then and claim and jump to the nearest catch block so we'll go up here okay so it started raining really hard I don't know if you guys can hear that through my mic it's really hot and and what is happening then we are returning here the response so once that response is in that range 200 to 299 we get the successful message that means the request is successfully been sent and fetched when we get this and we're gonna return the response to as a Json Dara forgot to do this here we anyways let's move on to the second then now why do we have a second then here this method is Chained after the previous one to handle the successful parsing of the Json data obtained from the previous right so the previous then block was used to check if the response is okay and then return if the response is okay this is is used to set the response data to that state function sorry and then we are storing into that just like the other example I'm talking about and second catch why do we have the catch here so there is another catch here why do we have this we have this uh chained after the previous one to handle any errors they may occur during the process of fetching or passing the data if any error occurs the Callback function inside this will be executed and then we will log this to the error right let me just hide this because I forgot one thing here I can see it right there this error [Music] okay that's much better so that's it this is how you use promises so we have done fetching the API data using the async await you have seen that we have seen fetching the April using the axios we have seen the how we can fetch data using the promises and without this if you're using a typescript file you have to define the type of the data You're Expecting right so we have created this interface which we pass it to the use state which will store the data from the API so it knows that I'm fetching a name which is a string I'm fetching a date which is that if I change it to a number [Music] foreign anyway so let's go ahead and that's it I think this is the end of this tutorial so I hope now you understand that um how we can fetch the API data using the fetch method with async await the asynchronous function with the promises and with the third party Library XPS so now you may be wondering which of these three ways of handling the API data we should use actually right um actually the choice of approach depends on the specific requirements of the context of your application each approach has eight advantages and its case use cases so for async or weight function for this function let me just comment it out while I'm talking about this I'm gonna comment this one okay so it's working so with the async await function what advantages do we have it provides more concise and synchronous like code structure making it easier to read and maintain as you can see it's pretty straightforward and it allows you to handle the error using the try catch blocks like making error handling no straightforward and the use case maybe it is a good choice when you have multiple asynchronous operation and if you prefer more modern and cleaner syntax of handling synchronous function right so let's convert it out move on to the next one [Music] now with the axios approach advantage of this approach is it's because it's a widely used library for making HTTP requests and comes with features like interceptors request response which I will do more video in the future and it's it's really easy to handle error it's it supports both promise based and a single with syntax giving you flexibility in how you can handle the response or errors right the use case for this would be the like it's a good choice when you need to make a complex HTTP request and handle them with ease and it is particularly useful when you want to implement features like request response intercept Global error handling and Etc so let's comment of this one let's come to the promises right so what are the advantages of using the promises if this the fetch API because it's a built-in browser so there is no need to install any external library and like the xeos and it is supported by most of the modern browser a use case for this would be because it is a good choice for simple scenario where you need to make a basic HTTP request and handle simple response so for our our app I would prefer this method over the other two method because it is a really simple application which is making a response we're fetching some data and we displaying to the user if you prefer to use native browser apis without external dependency always use this approach with the promises right in general if your application is modern and supports modern JavaScript features the async await approach is Good Choice as it provides a clean and more readable code structure for handling asynchronized operation right but if you prefer a wonderful and feature Rich library with like broader browse sport actually is an excellent option however if you are working on a small project or prefer to use native browser API without additional dependency using the Fetch with promises just like in this application I'm going to leave it with this one because it can be pretty straight forward and while uh viable solution right ultimately the best approach depend on your specific use case team prefer Frozen and project requirement now with all that our tutorial ends here and we don't have any errors I just want to check it yep everything is clean just like we expected here and um now we I hope you have gained a clear understanding of how to fetch API data in react while also handling the required types that are expected from the API response thank you so much for watching this video if you found it helpful please consider hitting the Subscribe button to support me and stay updated for more content like this together we will Master typescript with react if you have any questions or topics you would like me to cover in future videos please feel free to leave a comment below your feedback is inevitable and in shaping the content of this channel keep exploring keep learning and keep building amazing things with reactant typescript until next time happy coding goodbye
Info
Channel: TSXpert
Views: 3,821
Rating: undefined out of 5
Keywords: javascript, typescript, react, reactjs, reactts, reacttypescript, programming, codding, studentsprogrammer, it, react projects, react typescript project, react+typescript projects, javascript programming, learn react, learn typescript with react, fetchingAPI, APIdata, reactapifetching, apitypescript, API, Typescript, React Typescript Projects, API data fetching tutorials
Id: 7j-BxqUhsR4
Channel Id: undefined
Length: 71min 30sec (4290 seconds)
Published: Wed Aug 02 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.