Axios Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up everybody this is john from coding addict and welcome to axio's tutorial video where we'll cover an awesome http library by the name of axios which makes data fetching a breeze and is a great alternative to good old fetch api well we can use axios in vanilla js as well in this project we use it in the context of react so my assumption is that you are quite comfortable with react library so things like use effect use state and all that if you need a refresher i have entire tutorial on react and i'll leave the link in the description in order to follow along you will need a star project and you can find it in my github just look for this repo axios tutorial react and once you get here just pick whichever option you prefer in my case i'm going to go with download option then i'm going to navigate back to my desktop i'll set it up over here and i'll probably rename it i'm just going to go with axios i want to open up my text error which is visual studio code and then it's my preference to always set it up side by side so i'll set up the text editor and browser side by side now this is a straight up react project basically i used create react app i just added some boilerplate so we can save a little bit of time and focus only on the logic and we want to go with npm install and mpm start right away and if you take a look at the source one you'll find over here a components folder where there's only one the title one which you'll see in a second and examples so this is where we'll do all of our work so we have first request all the way to interceptors again there is already some boilerplate so we don't have to waste our time on that and you'll also find the final one so this is a complete project if you ever need a reference and effectively the way we'll do our work we have app.js at the moment notice we just have the title and we'll import the file for example first request and we'll display the results on the screen and then we'll slowly start setting up the logic over here that is going to be the idea and like i said if you take a look at the final one you'll find the examples so the same folder only in this case it's a complete code so this is a finished project so if you want to run this you can definitely do so or you can just double check your code if you ever need a reference and if your result is exactly the same essentially if you see axiorys tutorial in the browser we can start exploring axios library in the project root you'll also find readme with all of the steps we're going to take during the project and the first thing i want to mention is the docs so if you ever want to reference the official docs of the actors library here is the link then after that we want to worry about the install and if we're using vanilla.js project then we can simply go with this script tag but since in our case we're using react project we might as well go with npm instead and the command you're looking for is npm install axios now i already added this particular library to the project and you can definitely see that if you take a look at the package.json but nonetheless why don't we install it one more time together of course this is up to you but in my case i'll showcase that of course we can use the command and everything is going to work as expected and i also want to go with npm start now i'll close the terminal i don't think i'll need it anymore as far as the first request we want to import axios and then we just need to decide which http method we want to use so if we want to get resources from the server we want to go with get so axios that is going to be the instance and then we want to pass in the url and if we have different methods then you can clearly see what is the method name so for post we're going to use axios post and in that case of course we'll need to provide more info as far as the method it's not just going to be the url but we'll cover that a little bit later so you just need to decide what functionality you want to perform as far as the server is concerned so whether you want to get the resources add the resources and all that and depending on that you'll choose a method now if you don't provide the method after axios so the instance by default is going to be get and in that case we simply need to pass in the url so if you don't add that get explicitly by default it's always going to be get anyway so we go with axios and then again for the last time we need to pass in the url now this does return a promise and the data is going to be located in the data object and when it comes to error it's going to be located in the error dot response and essentially our logic is going to look something like this where we're going to use use effect and we'll pass in the function in this case fetch data and i right away set it up as async since this does return a promise and i'll stick a weight in front of axios so we import axios from axios then we set up the function and we'll stick a weight in front of the axios notice here i'm just going with default option they get when we pass in the url show the server we want to use and then we'll wait for response and after that i'll log the response as well as the error just so you have a better understanding so now let's start setting this up where i want to close the final and i want to go to app.js and first let's get the first request so you want to import the first request from the examples because in there we already have the boilerplate code we'll just need to add the functionality now in my case i'll right away call this a setup and i won't change that name so essentially in the following videos i'll just change the path keep in mind that all of them have been exported as default so it doesn't really matter so let's go here to examples then first request and then i want to render that right underneath title and then in the console we should see some dummy code just so we can see that everything works so here i have first axios request so now let's navigate here and you'll notice the url now this url points to my server so i purposely set the server up for my rack course for vanilla js just so we can practice data fetching now there is a limit so if you'll see in a console a 429 response you'll have to wait for 15 minutes and try again and if you want to take a look at the other endpoints that are available just navigate to course api and these are your options and like i said we're going to be using this one and essentially this just returns an array of products and then each product is an object so that should be our result and effectively we won't display anything on the screen we just want to make sure that we get back the same result so i want to showcase how we can fetch these products from this particular url using axios so let's start working on that where first we want to get the axios so right after the use effect import we want to go with axios from and then axios library which we just installed and then we already have the use effect so now we just want to set up the function i'm going to call this function fetch data and it's going to be a sync right away we won't pass any parameters in here but we do want to set up try and catch and again this is not specific to axios we just need to keep in mind that this is a sync and using try catch is a nice way how we can handle errors similarly how we would use it with fetch again this is not unique to axios so let's go right away with try and catch and since we have a sync we can just go with const and then response and you know what let me close the sidebar go with response here then a wait then axios and then for probably the fifth time or sixth time or maybe the tenth time we want to pass here the url that's the first argument that we always want to pass in then let's log right away response just so we can see what happens right away also set up the error and error will be located in this error object under the response property so let me copy this sucker let's go with dot and then response and then let's keep on moving and instead of log let's go with fetch data let's invoke and at this point it says response is not defined okay so we have response here oh my bad it shouldn't be response and response it should be error and then response my bad and now check it out in the console we have this giant object with lots of useful info for example we can get the status as well as status text but what we're looking for is the data property essentially every time the server will send something back which in our case is that product array it's going to be located in the data so either you can destructure it here so instead of going response you can just set up the the structure and look for data or of course we can assign a new value so in the following examples we'll most likely take a look at the data option as well directly here but in this case let's just go with data and that is equal to response and then data again of course you can also use these properties as well if you ever have a use case so let's go here with log now and if we log the data we should see that entire array and there it is now of course we have all of the product now when it comes to response what's really really neat is the fact that axios actually treats all of the errors like the errors unlike the fetch because if you remember when it comes to fetch it only treats the network errors as errors and in order to showcase that let's go over here we have the url and now let me mess this one up and now check it out actually in the console right away i have the 404 which means that we're not successful and we also have this object like i said and again data will be located over here in the data property so if you want to specifically look for the message that is coming from the server go with error dot and response and data now if you're just going to go with error.response you see this entire thing and again what's really really cool that it treats for example 404 as an error which just makes things easier because fetch doesn't do that so that is going to be standard setup for the get request in axiorys where again we import axios we provide the url it returns a promise so we stick away in front of it most likely you will set this one up right away as i sync but technically remember you can still use them if you ever want to we want to invoke that function in user effect and if we're successful if we get this data back of course we can do whatever functionality we need to do so for example if there would be a state variable by the name of product you can set those products equal to this array then maybe render them in the component and hopefully you see where i'm going with this and when it comes to error the data is going to be located in error response data but if you want to see the entire error maybe you're looking for the status text then you want to go with error dot and response okay hopefully we're clear on the straight up debt request but what if we need to provide more options for example a request headers come to mind and for that we'll need to pass in additional argument and we'll set it up as an object now if you're using straight up get a quest then this is going to be second argument however if you're using one of the methods where actually we're passing in data to the server for example post then this is going to be a third argument and in our upcoming example i picked the api that is looking for the header and that is going to be that joke api and essentially we'll set up straight up get request so notice here axios and then url however the second argument will be an object and in there more specifically we want to set up headers property and after that the api is looking for accept header and we want to pass in this application json otherwise the api is going to send back the text and then we'll add a little bit of additional logic so let me close the file also let's navigate to app.js and in this case i'm not looking for the file first request i want to get the headers one so let me change the path and we're looking for the second one again i'll keep the same setup name i don't want to change that one and i also want to clean the console basically at the moment we just have a button here and every time we click on a button we log fetch a dad joke and underneath the button this is where eventually we'll display that joke so let's navigate over there like i said i'm using that joke api and this is the url you want to use and if you want to reference their docs you can definitely do so in my case i want to skip that and i just want to repeat that in order to get the dad joke we also need to provide the accept header and first i just want to showcase what is going to happen if we don't do that so i have a state variable by the name of joke i also have a function and as you can clearly see the default value is this one so now let's set up our fetch dad joke function where we get the joke from the api so at the moment every time we click on a button we invoke on click and then we have the log so let's change that one around where we wanna right away set up try and catch let's go with const and then response is going to be equal to await axios notice here i already import that one and let's just provide the url so in the initial setup i'm not going to provide that header the accept one so let's log this one and once we click i said we're not going to get our data in the json format so let's add that additional argument set it up as an object if we want to provide headers the actual property name is headers and then in here this is an object and then we pass in the accept header we want to go with application and forward slash json and now what you'll notice if we refresh and if we fetch in the data you right away have the joke we're gonna get the id the joke as well as the status and just to showcase that we can the structure right away i'm not going to look for response data i'll write always say hey get me the data out and then let's log this sucker more specifically data joke again let's try to repeat that one more time and now of course i'm going to have the joke so at this point we want to set our state variable the joke equal to whatever we're getting back from the server so let's run this so set joke data data dot joke and then when it comes to error simply log if there is any so error and then response and now the result is going to be falling where every time we'll click on a button we'll actually fetch a random joke from the dad joke api and we'll display result over here so that's how we can set up additional info to our request more specifically headers we add an object as additional argument and in there we look for headers property and whichever header you want to add okay and now let's take a look at how we can send data to the server and we do that with a post method which references the http post method and in here not only we want to pass in the url but actual data we want to send to the server and additionally if you need to add more info about the request for example authorization error comes to mind then like i mentioned in the previous video we'll pass this in as the third argument now that said in the following videos we'll cover global instance will cover custom instance and also cover interceptors if you use one of those approaches most likely you can just bypass passing this directly in the request again we'll cover those things in the following videos so you'll see what i'm talking about now as far as our example i already have the app.js open and here i have the setup and i'm looking for the file number three so three post request and i'm rendering it on the screen now as far as the file in here i have the form where i have two values name and email now both of them are set up as state values right away with your state and i'm also right away importing the axios instance then notice how i have handle submit right away prevent the default and also i just want to check whether i have the results if you take a look at the inputs i have the value and i also have the on change like i said i already prepared this boilerplate so we can just focus on the axios so here's the main goal i have the course api server and on there i have the route by the name of axios tutorial post so this one you cannot test out in a browser because it's looking for the post request more specifically in the request it's looking for name and email now we're not going to save the user in a database or nothing like that but if we provide both values we'll get back successful response or if one of them is going to be missing then we'll get back the a response and that clearly is going to show us how we can send post requests with axios and let's start simply by just making sure that we can see both of the values so let me go to the input i'll say john at gmail.com and once i press on login i see both values okay so now we can start setting up our request where we want to go with try and catch let's set up the response right away that one will be equal to await then axios then post and like i said first we pass in the url so this is where we'll be sending that data and then comma and actual data we want to send and i want to grab these state values and i'm fully aware that we have a shorthand for this but initially let's just go with name equals to name and email equals to email because i think it's going to be easier to understand in the beginning then let's log the sucker so let's say your response and i'm going to be looking for data right away and the same goes for the error so let's go log error and then respond let's save this and now i want to navigate to the big browser because i want to showcase the network request so let's navigate over here let's refresh and we're going to go here with john and john at gmail.com let's press login and now take a look at our request so first of all notice the request method is post so now we're sending data to the server and also we can take a look at the payload right away so this is what we're sending we have name and that is equal to whatever we have an input and the same goes for the email now when it comes to response since we provide both values in response you'll see message user created again we're not saying this in the database but the general idea is going to be exactly the same where this is the response you're going to get back now most likely you'll also get the json web token but again that is besides the point and then i have the user name john email and then also a full name where i just add the doe and then if you want to test this out whether everything works maybe you're like okay this is just a standard response that you're getting back let's go with susan and you'll notice that server again is looking at both of those values and if they're provided then again we get back the user with this susan though and now let's also test it out what happens if we don't provide one of the values so first let me just shorten this up like i said starting with es6 we have this ability for shorthand like so so name is equal to name email is equal to email and then i'll send the request without providing the name value and yes i'm fully aware that normally we're going to check this in the front end as well but the main goal of this video is to showcase what type of error response we're going to get back so let me remove here the name in the input and now what you'll notice in the console is an error so we have 400 bad requests and also in the data we'll have this message property would please provide both values so that's how we can send post requests using axios where it returns a promise so most likely we'll stick a weight in front of it axios dot post so that's the method name then we pass in the url and then the data we want to send to the server okay and now let's take a look at how we can set up a global axios instance and what that means is that we can add some kind of functionality by default so every time we'll make a request with axios instance that functionality will be added now in the readme you'll find quite a few options but in our example we'll just use the first one where we'll add the accept error and we'll set it equal to application json and again there it is that every request which is going to leave our application by default will have that accept header and also in the next video take a look at the downside and how we can fix that using the custom instance and there will cover the base url which again you can also set it up on the global one as well and our starting point is going to be following where we want to navigate to app.js we want to change it around in this case it's going to be file number four and in here we have two urls one is to my server and the other one is actually going to a different server it's going to random user url because again there are some downsides if we use this global approach and i definitely want to showcase them so we have this file and we want to set up straight up get request with product url however we want to add that functionality the accept header to our default global axios instance so first let's create a file so in the source i'll create a new folder i'll call this axios let's create a file here let's say global js and here we want to import axios from axios then let's set up that header so axios default then headers then dot common and we're looking for the accept one so accept header and we want to set it equal to application then forward slash and json let's save it now we want to import this file in the app.js or index.js basically when our application spins up so let's say here import now we're looking not for the axios library we're looking for axios folder and then global jazz and now if we go to global instance and if we just import axios from axiorys again this does not change as long as we have invoked that file and as a quick send out if we just import we automatically invoke that file so this logic will be set up right away if in the global instance we import this axios and if we set up the request you'll see something interesting in the devtools so let me go here where i have the global instance um let's right away set up the try and catch i'm gonna go with response one since there's going to be two of them we want to go with weight axios and product url so now i'm going to navigate big screen because it's going to be easier to showcase so i have in a console nothing since i'm not logging technically we can log of course just so we can see that everything works so let's go with response one and we're gonna get back the data now that is not the important part the important part is if we navigate to a network tab more specifically if we take a look at this react store product which you'll notice in the request header is this accept one so any request you'll set up you'll have this accept header added because we did set up that global instance and again you have tons of things that you can set it up over here but we're only gonna cover the first one and the second one we'll cover with the custom instance now let me right away showcase the downside so let me go back to the global instance and now let's set up second response so let's copy and paste let's say here response to it's not going to be product url it's going to be a random user url and keep in mind that these are two different servers so one is my server which maybe for some reason is looking for that header and we have totally different server and in the console we will see still the response one again that is not the important part the important part is if we again take a look at the network tab now we'll have two requests so one is going to be to my server react store product and the second one will be to the random user api but for both of them if we'll take a look at the request headers we will see this accept an application json which in this case you can make an argument is not a big deal but we need to keep in mind that if we have something sensitive like for example json web token we don't want to start descending left and right and this is something that we'll fix with a custom instance okay so now we're familiar with global defaults and we also cover the downsides so what is a possible fix well we can set up a custom instance where we create a new file we import axios but instead of defaults we go with create again we pass in the object and here we have multiple options if we want we can set up the base url so if you know that you'll be setting up multiple requests to the same server you can add here the root url and then the specific url when you actually invoke this one and don't worry you'll see that in a second and the same goes for headers instead of setting this up globally to all the requests made with axios we'll add this header the accept one and only when we invoke auth fetch which is the name in this case of course you can name it however you'd like only then we'll add that and as always i think the example is going to be the best helper so let's first navigate to app.js and yes i purposely set up a new file for the example even though the most logic is going to be exactly the same just so you have a reference for the global setup as well so first we're looking for custom instance then we won't use this anymore so we can just remove it let's save it now we have custom instance and this is exactly what we should see over here as well so now let's navigate to the axios we want to create a new one in this case i'm going to go with custom js then let's import the axios from and we're looking for axios here let's create that instance so my case i'll call this auth fetch so let's say here create we want to pass in the object and like i said i want to set up the base url so if i take a look at the custom instance you'll notice that i don't have any more here this url the one that leads to my server but if i take a look at the global instance notice this https and then course api and react store product so in this type of scenario normally you can just take the root url in this case that is course api in some cases it's going to be longer we can add this one to the custom instance and then every time we make a request we just need to say well what is the exact path in this case it's going to be forward slash and react store product so let me navigate back base url and yes as a side note you can set this one up in default as well like i said in the previous video then just so i don't make some dumb typo let me take the first part now it's up to you if you want you can take the forward slash and then you just need to provide react store products in this case but i actually prefer getting everything up to the forward slash just makes a little bit more sense if i provide the forward slash when i invoke the instance like i said that is totally up to you this is going to be my base url then let's add those headers right away as well so let's set up the accept and we're going to go with application forward slash json now we do want to export this so export default and we're looking for auth fetch and now let's navigate to the file i want to go to custom instance so i still have this random user url and above it we want to import that custom instance as well as axios instance so for the random user the one that's going to some different server we'll just use the default axios instance however for my one we use that auth fetch because that one has some goodies so let's say here import auth fetch and this is coming from the custom one and also let's set up the import and axios from and just simple axios so when we set up the fetch data first we want to go with try catch just like we normally would then let's go response one and this one will be equal to await and then off fetch and remember we already have the base url so like i said the forward slash part is up to you but in my case i prefer setting this up without the forward slash i'm talking about the base url right now so when i'm setting up the instance when i'm invoking it then i just add that forward slash it just makes a little bit more sense to me but you don't have to do that so react store product so that will be the url and then the second one const and then response two and in this case i'm not gonna log it i don't see the point again the main point is what we have in the requests not whether we are getting the results or not so await axios and now let's go that random user url and if we'll take a look at the browser let's refresh again we have two requests going out but if we'll take a look at the first one we'll see that application json and notice again how we were successful even though we did not provide the entire url because we already have the base one and if we'll take a look at the other one the other request we'll have actually here default except one with text plan as well and this clearly showcases the fact that with a custom one we can pick whatever stuff we want to add to our request so now every time we'll use this auth fetch instance well this base url and whatever default setup we add over here but then if we just use the normal axios instance it's just going to be a standard request and as you can see this is totally up to you more specifically depends on your application if you have a setup where you can just add everything as a global instance so if you don't have anything that possibly might be a security issue then you can just add those things to a global instance and you're good to go however if you have a situation where you need more detailed setup where effectively you want to add this only to specific requests then of course custom instance makes a little bit more sense beautiful and our last topic is going to be interceptors which are functions that axios calls for every request and we can use them to transform the request before it leaves the application as well as add some custom logic when we handle the response in general interceptors make way more sense if you have complex application for example authentication comes to mind so we'll come back to them once there's actual need in our project this is just introduction to interceptors so in our examples we'll mostly just log stuff also we will set up interceptors on our custom instance but please keep in mind we can add them exactly the same to our global instance instead and like i said basically they are just functions we go with custom instance in this case then interceptors and then either request or the response so this is the outgoing request and then the incoming response then that use and then we pass in two functions so in the case of request in the first function we access the request the outgoing request and we must must must must return this request otherwise it's not going to work and as an example we can add the header here notice the syntax is very similar to the default one we just don't use defaults we go request whatever is the parameter name as always you can call this mambo juice then headers then common and in this case we're just adding the accept header but yes you can add authorization header and all kinds of things and like i said in our case we'll just log just so you can see that it actually works then if we have error we will have return promise reject error and the same goes for the response one we're in here we'll log the response that we successfully got the response back we need to return this and we also have the error one and i'll talk about this one once we actually set up the code because this is the place where we can make some global app decisions that affect all of our requests and you'll see how cool is that so first let me showcase that in the app.js i have setup i have six interceptors file and there's not much there again i have the url back to my own server and we'll just be looking for the custom instance that we'll set up in a second and then we just want to invoke it and then you'll see the logs in the console you'll also see the header and we'll also take a look at how can add some logic based on the error that we're getting back and actually want to start here in the axios we want to go with new file and we'll say interceptors hopefully i'm spelling this correctly and we still want to get the axios and all that and you know i think it's going to be better if we just take this entire thing i think it's going to be faster again like i keep saying you can set this one up on the global instance instead i'm just using this example so i have this auth fetch let me take this one out so i'll leave this base url in place then we want to go with our first interceptor so let's just set up here auth fetch then interceptors dot and then i'm going to go with request use and for time being let's just pass in two empty functions because i do want to copy and paste this to save a little bit of time so let's set up over here the second function let's copy and paste and it's not going to be a request this will be the response like so then in the first function we want to access the request that's going out and again it is at the end of the day of course the parameter so we can set up here whatever we want so in my case i'm going to go with request then in the function body right away let's return that request because it's very easy to forget that and the functionality is not going to work so we set up the request and in here i just want to add that accept header just so we can see and also i want to log this i want to say request sent and right above it let's go with request then dot headers dot common then the name of the header which in this case is going to be accept and let's set it equal to and i'm just going to go with application json now i can see that i have tiny bug here there is no dot just accept so that should do it then we also want to deal with error and we want to go with return promise dot project promise promise dot and then reject then let's pass in the error and now let's work on the response one now as far as the successful response let's just log that so let's say here response and again we want to return that so return and response and let's just say that it happened so log and got response and we also have the case for the error so let's say if we send the request and we get back the a response whether that's 400 whatever that's 401 which is authorization error or it's 404 means couldn't find the resource and for now let's just go with error and then log error response and then i said we'll add a little bit more custom code just so we can see how everything works so error and response let's save this now we want to navigate to the interceptors we want to get that custom instance from the interceptors in this case though so let me open up this file and in here we already have the url okay that's good let's go with auth fetch we're looking for axiors and then interceptors we have fetch data in place and instead of log let's set up the try catch and then we're going to go with const and then response equal to await then auth fetch so off fetch remember we already have the base url so we just go to react store hyphen and then product and once we save we have in the console quest send and got response which means that now in here we can add whatever custom logic we want and don't believe me we can navigate of course to the browser i can refresh and you'll see that again in the headers there's going to be that except one and again this is just an example of course we can add whatever headers we want over there or some other logic for that matter now where this is going to be really handy is when we are dealing with authentication because we need to keep in mind that this gives us an option to set up code for the entire application so for example if we're getting some type of response again for the application that would be 401 we can log out the user in all of the requests so we basically don't need to repeat ourselves you can think of it this way so first let me just go here to the interceptors and let me mess up the url so instead of react store product let me add one more s so still get the logs and all that okay that's good the request is still sent but now we're getting back the response so route does not exist so this is our data and notice the status over here so we have 404 so here's what we can do we can mimic some global response that we would have in the case of 401 in this case however we'll work with 404 so i'll keep the error response but i'll say if error dot then response then dot status and if it is equal to 404 in this case then let's just set up some kind of log and we'll say do something now in our case again that something is just going to be locked but normally this is where you would communicate with your application state and we'll say log here and in the log let's just write not found and then below this if one let's just go with return and then promise promise and then reject so we can still get that error in our instance so over here where we have the catch but the idea right now is that let's say for all the requests that we will set up if the response is going to be 404 then we'll have this not found again normally what's going to happen you'll have 401 and then let's say you log out the user which is by the way something that we do in my mark course so let's refresh here and now check it out since the response is 404 in here we have this custom logic that has this not found so that's how we can set up interceptors in axios
Info
Channel: Coding Addict
Views: 52,083
Rating: undefined out of 5
Keywords: axios, axios tutorial, axios tutorial react, axios data fetching, axios http requests, axios http library, axios get request, axios set headers, axios post request, axios global instance, axios custom instance, axios interceptors
Id: mS48F0swwAY
Channel Id: undefined
Length: 48min 28sec (2908 seconds)
Published: Wed Apr 06 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.