React Axios API Requests | Axios with React JS Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome hi i'm dave and in this tutorial we will be adding the axios package to our react js blog application and it will help us request data from a development api that we will set up with json server axios actually makes requesting data easier than using the fetch api so let's get started i'll go to the file tree and i'm going to click new folder and the first thing i'll do is create a folder named data and inside this folder i'm going to create a file named db.json and then inside the db.json we're going to put data you could actually copy it and modify it from our app component and i'll open up the app component here as you can see we have a static state right now for posts set in the app component and here we have four test posts and their objects inside an array you could just copy these and put them in there i'm already going to paste in my formatted json and you can see it's just a little different than we have in the state here we have an object and we've given the object the name posts or the property posts and then the value for this property is the array with all of the posts like we have in the use state in our app component right now notice each of the properties are within quotes and that is not the case in our javascript over here in the app component so as you bring those over ensure that you are formatting them like you see here in the db.json i'm going to go ahead and save this and now that i have the db.json file inside of our data folder i'll go back to the app.js and i'm just going to remove everything in the post state and replace it with an empty array which is how we want to start out and save and that is really all we need to get json server up and running so i'm going to collapse the source folder now and click on the package.json because we're going to add axios as a new dependency so after we install it you should see it listed inside the dependencies of your package.json file quickly go to chrome and here at npmjs.com then slash package slash axios you can see the details for axios and there's documentation here as well and i will put a link to this in the description for this video going back to visual studio code i want to open up a terminal window in windows i press control and the backtick you could also go to the terminal menu at the top of visual studio code to do that as well and get rid of the help menu there that i opened by mistake and now we can install axios as a dependency so i'll type npm i and then axios and dash s is a habit of mine it's actually not required because it will save it by default and it will save it as a production dependency so we can just do npmi axios i'm going to press enter and when this finishes installing we'll go ahead and get started applying axios to our project you can now see axios has been added to our package.json file and we are ready to begin adding axios to our project let's close the terminal window and now let's open the source folder we see in the file tree and let's add a new folder inside the source folder and let's name the folder api inside the api folder let's go ahead and create a file name posts and then we'll put js of course post js and now that we've done that we can import axios from axios and now we need to set the base url that we'll use for axios throughout the project so we can just set export default and say axios dot create and then a parenthesis and then a curly brace now on a separate line we can define the base url property and we'll set this to our http slash local host and then we need port 3500 that we're going to launch our json server on and that's essentially all we need in this file and now axios will continue to use this base url and of course when you would take this project live you would need to change this base url to whatever url you got at your host okay now that we've set the base url for axios let's go ahead and open a terminal window and inside this first terminal window let's launch json server so we'll type npx and then json-server dash p and then 3500 for the port and then dash w for watch and that will be data slash db json press enter and that should launch our json server instance and after we get that started we'll go ahead and launch our react app in another terminal window okay to open a second terminal window i'm just going to click the plus sign here and now you can see we've got a little tree on the right that shows our different terminal windows in this terminal window i'm going to launch our react app just by typing npm start and once we get this started we shouldn't see any posts because we've changed the state but then the react app will show any changes we make as we add axios into our application and now our application is loaded with no posts to display as we expected since we cleared out the static state i'll go ahead and resize the window so we can see it on half of the screen and then i'll resize visual studio code as well and now we can work on our code on the left and view chrome on the right i'm going to close the terminal windows although they will continue to run and we can reopen them at any time also going to collapse the open editors area over here in visual studio code so we can see a little bit more of the file tree and we're ready to begin in app.js okay in app js i'm going to hide the file tree quickly i do that by pressing ctrl b in visual studio code i'm using windows it may be different in mac and linux but what we need to do at the top is import our api so i'll just add another line under where we imported format and here i'll import api and this will be from dot slash api but remember that's a folder and we can see visual studio code shows us that so we'll select that and then we have posts inside the folder so now we've imported the api and we can use it in the application i'm going to scroll down and underneath our use history line here on line 20 i'm going to press return and start another use effect and this use effect is where we will fetch our data and we only want this to happen at load time so our dependency should be an empty array inside this use effect we need to define our fetch function and i'll call this fetch posts and it should be an async function inside the async function we're going to have a try block and of course to follow that up a catch block where we catch any possible error and now we need to simply define how to use axios and we'll define a response just like we would with fetch and we'll set this equal to a weight api remember that is the axios instance we're importing and then we can use get and this is where axios becomes very easy to understand we actually use the verbiage the words that we would in a crud operation possibly in api usage so like http uses get post put delete there's patch and a few others but we're only going to use the basic crud operations so get would be our read operation in crud and so now we just need to say what endpoint we want with that base url and of course we only have one endpoint with this application and its posts so we'll go ahead and define that now this replaces fetch and then what's so nice about using axios instead of fetch is axios automatically creates that json we don't have that second step here where we have to define data and set it equal to response.json another thing that is nice about axios is it will automatically catch the errors when they are not in the 200 range of http responses so before where we would have said if the response dot ok is false with the exclamation mark there we don't have to do that either axios will automatically catch anything outside of the 200 range so what we can do now is just set our state with set posts because if we get to this point an error has not occurred and we know it's already in the 200 range and our data is going to be in the response dot data now you may see some at this point would say okay if we have the response which we should at this point it should only be in the 200 range and they might say if we have response dot data and you could do this to be extra careful if you want to i'm not going to do that because right now i know i've got a response in the 200 range and if i have that our json server is absolutely going to send data back and if you are working with somebody else that's developing the back end you might already know that you will be getting a response in that 200 range if not that is how you could check for that to make sure you have a response and response data i'm just going to leave it like this and we can set that response right here for the posts and that's as simple as it is really that is using axios to get the posts and setting the post state right there now axios catches those errors that i mentioned and what we can do this is directly from the documentation we can say if this is not in the 200 response range then i'm just going to copy and paste some things directly from the axios documentation and axios will provide these errors and so you could log all of these different things if you wanted them so you would get error dot response dot data right here and so if your back end was sending a message at this point you would actually receive the message if that was the property like that it just depends on what the back end is delivering when it's not in the 200 range so you have to know what you're dealing with on the api that you're working with to actually know what property to pull out of that data you could also get the status and the headers but then axios will also catch other possible errors here so what we can do is say up above this we can say if error.response that means we've got a response property well here just need the one and now put the curly brace at the end and this is when you'll see these responses but then we can say else and this means error.response is undefined so if that's the case we can just log the error message and i'll copy and paste this in but we've done this before this is a template literal and now we're getting the error message property and so here we know we did not get a 200 or we did not get a response at all i'm sorry here we know we didn't get a response in the 200 range but we got a response from the back end api here there was possibly no response or we got a 404 or something else occurred but this catches all the other errors right here again this is directly from the documentation for axios and it handles those errors very well so we can pull out extra data if we need to and we can define between those all of that said our function for fetch post is now defined but what we still need to do is call fetch posts here inside of the usefx so let's save this and now we have our posts once again over here on the right and so our use effect works as soon as the page loads and of course our development server loaded the page as soon as we saved our changes and we now have those posts now if you remember we can post a new blog or make a new post on the post page in our application so the next thing we need to adjust in our application to use axios is the handle submit function handle submit has a few lines of code that are just a little longer so i'm going to expand visual studio code we will come back and show the application after we complete this code edition for axios and of course this would be the create portion of a crud application the c in crud where we're creating a new post so after the line 54 that defines new post we need to start our try block here and of course i'll delete that ending curly brace but everything that we see here is really going to be in the try block because we won't want to make any of those things happen if we fail our attempt here but we do need to go ahead and catch an error again and here instead of everything i posted above from the documentation for axios we'll just console.log and we'll once again have a template literal so i'll say error and then inside here we will put the error dot message so at least we know we're grabbing the message and logging it you could expand upon this you could put what i did above in the use effect when we're fetching and handle the errors how you want to but at least we are acknowledging we might get an error here and this is what we'll do for it in this development application so in the try block we need to define a response once again so we'll say const response and we'll set that equal to await api but now we'll use post instead of git because we're posting a new uh blog post and then we need to define the endpoint posts and then we're going to pass in the new post and that is the data we're sending after that let's well we don't need a new line let's just look at all posts because we need to alter that we're going to take all the posts we had previously and now instead of the new post here we're going to use the response dot data this should be the same as the new post actually it should just be the api sending us the data back and confirming that we'll go ahead and use response.data here instead of the new post and then we can set the post to all posts we can still empty out our controlled form that has the title and the body and we can use history.push to go back to the actual blog and see the full list in the feed and so nothing else really changes we're just using axios and it's really that simple to send the new data and then we're going to update the state with the actual response we get from the api as well and get that dot data out of the response so let's save that and i'll resize visual studio code again and it looks like we have a problem here because i didn't put a sync at the top of the handle submit so we can't await without it i'll put async on line 50 where we define handle submit and we should be good so let's make a test post for tutorial and here is my test post and here it is with that working let's go ahead and set up the easiest part of the crud operations which is the delete we've completed the read which was git and create which was post let's go ahead and add the handle delete i need to remember the async above here as i had to add later inside of the handle submit but we'll put it right away here with handle delete and then we'll start our try block and as before everything we already had is going to be inside of our try block then after that i'm just going to copy the catch block from the other function and put it here you can expand on that as i discussed with axios documentation if you want to and here inside of try we will not get a response we just want to await the api call delete and now i'll put a template literal because we need to pass in the endpoint post but we also need the specific post id to be passed along and after that everything else should essentially be the same so let's go ahead and save and now let's go to the detail page for this test post for tutorial and delete the post and everything seems to be working as it should for the delete operation as well and now the most complex operation of the crud operations we've got create read and delete completed but is the update and we haven't really added an update component to our application either so we're going to need to do that but first i'll create the function and let's just call this handle edit because we're going to edit a post and again this will be async and we need the id now inside the handle edit we're going to need some new state as well so let's scroll up to the top and just like we have the post body and post title let's create an edit title and edit body so i'll copy both of these and come down here and let's go ahead and just select post title both times and then change post to edit and i'll change this one to a capital e and we can do the same here for post and change it to edit and change this one to a capital e as well so now we've got edit title edit body set edit title set edit body and we use those in our function here for handle edit we're going to start out though needing the date time and the new post much like we do in this function above so i'll just copy both of these down and in here i will paste both of those the date time will change or it will not change actually the new post let's call this updated post and now instead of post title i'm going to have edit title and let me expand visual studio code for now instead of post body we're going to have edit body because this will be a controlled form where we make the edits as well and so we need those pieces of state for the controlled form now we can start our try block and of course after the try block we'll have the catch block and i'll just copy that down as well so now we can put our information inside of the try block we'll start with a response and we'll set that equal to a weight call our api and now we'll call put we could use patch if we were updating specific fields but here we'll essentially be replacing the entire post so we're going to use put and we'll put in the endpoint posts but again this will need to be specific to the id of the post after that we'll be passing in our new data which is the updated post okay now that we have got the response back from axios and the back end api we use set posts here but this will be just a little more complicated than we have previously uh completed a set post like we did up here where we just passed in all the posts after we defined the post because we need to use map that is if we didn't use map we would be creating a array of posts here but we'd still have in the old post as we added in the new post as well and we need to eliminate that old post and just add in the new information so with map we'll have each post iterated through and map creates a new array which is exactly what we need so we'll check the post id and if is equal to the id we passed in this will be a ternary statement and we'll say okay let's use the response data which is the new post information if the id is equal to the post id passed in if not let's just go ahead and pass in the post as it is so that means only for where the post ids match will we pass in the new data which is essentially the updated post but we're going to use the response data here destructured with the operator right here and if not we'll of course pass in the post as it currently exists because that does not need to change so that will update our post state and now we'll still need to set edit title back to blank and then we'll also need to set edit body back to blank because again we don't want to hold that data over for the controlled form in any way after that we'll use the history once again and push so we go back to the main feed so we can see our edited post amongst all the other posts and save that should complete the handle edit function let's go ahead and resize visual studio code just to make sure there were no errors as we saved but it looks like the application went ahead and loaded as expected right now we have no way to get to a new component and we don't even have the edit component yet so let's create the edit component and the pathway to get to it i'm going to show the file tree again in visual studio code i'll highlight the source folder and then i'll create a new file and call this editpost.js once i've done that i'm going to go ahead and expand visual studio code again i'm going to press ctrl alt and the letter r to use my es7 react snippets and here i'm going to type underscore rafce to get that functional component you don't have to do that you can type this out as well if you do not have that extension i'll link to the extension in the description below okay we need to make some imports at the top of this component the first one is going to be use effect and after use effect we'll say from react then we'll also import a couple of things from react craft one is use params and the other is link and it's not just react router it's react router dash dom visual studio code wants to help but it's got to get that part right okay in edit post we're going to be bringing in some props here and there's enough i'm going to put them on a separate line we'll need all the posts we'll need our handle edit function we will need the edit body the set edit body we'll need the edit title and the set edit title after that we can start in on our function and this is really a combination of our new post page where we created a new post with a controlled form but also our post detail page where we pulled in the post detail from a parameter and that's why we're using use params so we're going to start off here in the function and i guess i came down one line too far i'll create this id just like we did in our post page to get the post detail and we'll use params to get that id attribute that we're going to set in the route and then we need to get the specific post so we'll set this equal to post find and once again this is just like we did on the post detail page and this will be post dot id to string because when it comes out of the param in the url it is a string and that's what we're matching and so we have to set the post id2 string to actually use strict equals you could just use the double equals and not do the two string parts so it would be your preference which way to go there but now that we have the post and the id we can go ahead and use effect and this is when this loads we need to pull in this data and set the state for that so let's go ahead and say we're going to put in post set edit title and set edit body as the dependencies and now inside use effect we'll actually need to set the state for both of those we'll say if we have a post because there is a chance the page could be requested and a post would not exist so we'll say if we have the post set post title and this will be post title and then oh i'm sorry not set post title it would be set edit title here we go edit title and then set edit body and it would be post dot body here now that we have those we've set the state and so the form will already be filled out and our controlled form will be ready to edit the existing post the body of the page itself will be much like the new post page so let's just go to the new post page and select from the beginning of the main element to the closing main element and then go back to our edit post page where we can just highlight the divs and replace those with what we have on the new post page we'll leave the class name new post the same so the form here is formatted just like it is on the new post page so we won't change that however after the main element let's go ahead and put a curly brace and say if we have an edit title so the post will need to exist for us to have set an edit title and then we can put a curly brace afterwards but you can see visual studio code doesn't like this right now because in jsx you have to have a parent element and currently we do not have a parent element set we have oh i didn't mean to put it after the main actually so let's change that and put it after the form and tab this curly brace over not getting the tabs i want with the current error here and the error means we need to set a fragment in here as the parent element and now you can see visual studio code is much happier and doesn't have all the red lines so let's tab this over and then tab over here we go because our h2 and our form were neither one was apparent they were sibling elements so that's why jsx and visual studio code would not accept that now that we've done that let's change this new post title to edit post and let's go ahead and update the form a little bit we can keep the same class name here new post form we want the same formatting from css but handle submit will not be called an on submit instead here we will prevent default as we often do with the form inside of the on submit call for the form so when that happens that means inside the button here we're going to need to have an on click and we can set this equal to an anonymous function and inside this anonymous function we'll call the handle edit and we need to pass in the post id here and that's why we're not doing that in the on submit area now for our controlled form to work we need to go ahead and update some of the names here instead of post title would be edit title instead of set post title it would be set edit title and that would be the same here instead of post body it's going to be edit body instead of set post body it's going to be set edit body we could change the ids here but we know this component will not load at the same time as our new form or our new post form so we don't really need to they'll only be one on the page at a time so this should work for us once we save these changes we've created our new component but it is still not being routed to in the app.js we still have no way of getting there so let's go to our app.js and let's scroll down to our routes and let's copy this post with the exact path and paste it below we can remove the exact we're actually going to change the path to edit and then we'll need to have the id parameter afterwards so there we have edit and slash id parameter this will not be new post it will be edit post and now let's pass all the props we need here we need posts equals posts instead of handle submit this will be handle edit and now instead of post title we'll have edit title i should have selected both of those edit title i will do that now so here instead of set post title it will be edit title post body will be edit body and set post body be set edit body now we've got all the props being passed and we've got the correct route in we just need to create the link and have a way to go to that route let's quickly go back to our edit post page i just thought of something that we didn't complete we have the if edit title exists which essentially is saying if the post exists we're going to go ahead and show the form but if not and there is the chance that a post will not exist and then the page could be requested we need to go ahead and update this this shouldn't be post title this should be edit title but here this says if we do not have a title essentially if the post does not exist we need to pass in our post not found information here which is where we use the react router link to go back to the home page so now we've completed the edit post component and back in the app.js we completed the routing and so now that we have the routing we just need to create a link to the edit page well we have a delete button on the post page so that would be a good page to possibly put another button that would allow us to edit as well directly above the delete button we can use link which we've already imported above from react router and set this to and now we can put in a template literal and pass in the edit path and here this will need to be the post dot id now that we've created the link inside the link we can put a button let's give this a class name to differentiate it from the delete button here we'll say this is the edit button let's hide the file tree because i'm going to run out of room and after that we go ahead and put some text on the button we'll just say edit post that looks good let's go ahead and give the delete button a class name as well we'll set this equal to the delete button and we need the ending quote there we go and we save that and that's really all the change we need to make to the post page we may need to tweak the css just a little bit but this should be fine now one more late addition to the app.js that i didn't think to do when we put in the route would be to go ahead and import the edit post component at the top so let's fix that by coming up here right under the post page we'll say import edit post from slash edit post and save now let's look at our application see if we have any other errors everything looks like it's still loading correctly i'll just reload to make sure there we go let's click on testing a fourth post here we have an edit post button yes we might want to change the color with those new classes we added and differentiate maybe add a little space it looks okay if we click edit post we've got the post here ready to edit you can see the form is already filled out so let's say some more testing paragraphs instead with a few dots click and it looks like we edited our post just fine i'll click that and yes some more testing paragraphs looks good we could possibly go back to the home and create a new post and here this form is empty but it's a controlled post so we'll say another post once again and we've created another post so that's all working well we can possibly edit this post once again with an exclamation mark and yes it's working just fine the only other thing we might do to check for errors is right click and choose inspect or you could press control shift in the letter i and we'll check the console to see what the console is telling us as far as any errors or warnings but no it looks like it is clear we can reload and see if react gives us anything new nope it is fine so we're good to go from devtools there so let's go ahead and go back to visual studio code and then click on index.css and if you scroll to around 200 or around line 200 from what we've already had we can make just a few changes here first of all on my line 203 i'm going to remove the h2 missing h2 and postpage h2 and then i'm going to put a comma and i'm going to add new post and the paragraph for the new post class as well and instead of margin bottom i'm going to make this margin top so we can save that change and we should see that on the post page nothing has changed here but if we come back to home and go here we edit the post this looks good too now let's say let's try to edit a post that doesn't exist and the post not found page looks good as well now let's go back and let's here we are on the edit post page we want to fix these buttons actually this is on the post page and when we would click edit post it would take us to the edit post page but yes we want to fix these buttons and let's take the background color red out of the button definition and so now they're just plain old buttons here they both still have a white text color let's create the class delete button that we applied to our delete button and make it red and now that will change and then let's go ahead and create this edit button class that we also applied but instead of red we'll change that to the same color as the nav menu and now the edit post and delete post buttons look a little better we just need a little space there so besides the padding that is 0.5 ram let's say the margin right 0.5 room as well and now we get a little space between the two buttons everything seems to be working well we can read posts we can create new posts we can delete posts and we can edit post as well so we have applied axios and all crud operations to our application and we should be good to go and move on to custom hooks in the next tutorial hey thank you guys so much for liking the video if it helped you get started with react also i appreciate you watching and subscribing it's helping my channel grow take care and i'll see you again very soon
Info
Channel: Dave Gray
Views: 8,462
Rating: undefined out of 5
Keywords: React Axios API Requests, react, axios, api, request, requests, api requests, axios requests, axios with react, axios with react js, axios with reactjs, axios api, react js, reactjs, react tutorial, axios tutorial, react js tutorial, reactjs tutorial, react axios, react js axios, reactjs axios, react with axios, react js with axios, reactjs with axios, axios react tutorial, axios react js tutorial, axios reactjs tutorial, javascript, axios crud, crud axios, crud tutorial, crud
Id: ZEKBDXGnD4s
Channel Id: undefined
Length: 38min 31sec (2311 seconds)
Published: Tue Aug 03 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.