Introduction and Installation
React Axios and using the two together. If you haven't heard of it before, it's one of the most popular promise-based HTTP request clients available, and it's used all over the place, whether it's in JavaScript on Node.js. But in this example, we'll be setting it up on a React application, performing some gets and puts, and passing in data as JSON.
We'll start by installing it. And to do this, we'll just jump into our React application project folder and run npm install axios. This will add it to our dependencies in our package.json.
Creating an Instance and Making a GET Request
We'll start our project by running npm start and we'll browse into one of the components. In here, we'll import Axios by running import Axios from 'axios'. Now with this reference done, we can add this into our component. If we have an API endpoint we want to use, we can initialize Axios with an instance, and we do this by running const api = axios.create(). With this function here, we'll pass in an initial configuration with an object, and this will have a baseURL. In this case, we have one over here which we'll use, and we'll pass this in as a string.
We're going to access this API endpoint, and we're going to do it by performing a GET request to pull in all this JSON data. We're going to do this by calling a constructor which will run every time this component mounts, and with this, we'll call the API and perform a GET request. We'll just pass in a blank path, and we'll run the .then() command, which will get a response back. With this response, we'll have a bit of data here, and what we really want is to console.log out the actual data itself. So let's put this in here and take a look at our console to see if that came across well. There it is, and here's our array in JSON format.
Displaying API Data in a React Component
So how can we use this in React? Well, we can create some state, and in here we can have our courses. With these in here, we can have an empty array that gets populated when we run our constructor by running this.setState and setting them against the response.data that we get back. Let's apply this, and next, let's put these into our React component. We'll put this in our render method, and over here we'll call this.state.courses. We'll map this out, and for this loop, we'll set the name as course for an individual item, and we'll create an <h2> tag. In here, we're passing the course.title in here, and we'll also set a key so that each individual item is referenced properly. So we'll pass in this key, a course.id. Let's save that, and we'll see that it appears in our application.
We can use Axios to also talk to the REST API and create new items in our database by calling a post event.
Creating Data with POST Requests
We can do this over here by creating a new function called createCourse. For this, we'll have an async function, and this will then use api.post to just reference the main path and pass in a data object. In this case, it'll be an example of a course, so it'll have a title such as 'test', it'll have an ID such as maybe number 4, and an author such as 'test' as well. Then we can run a different query here called await. This is because we're using async, and we can pass in the response over here. Once we do this and console.log it out, this will be created in our database, so we can take a look at it, and it should react every time we select this function to run. In this case, I'm going to create a button for it over here, and for this button, I'm just going to reference the method that we've created in an onClick handler. So I'm just going to run this.createCourse.
For this button, I'm gonna select it here and refresh our application, and you can see that the test course has been created. Right now, our application isn't reacting very well because it's only pulling in the data on the constructor method.
Refactoring for Reusable API Calls
So we can pull this out and create its own function by calling getCourses here. We'll create another async function, and this time we'll clean up the syntax a little bit. Let's do let data = await api.get(), and this time we'll just pull in the data straight away as an object and return it so that we can use it in our setState. Then finally over here, what we can do is remove this and just call setCourses to equal data. We'll save that, and then we'll run this.getCourses in our constructor method. And we can also put this into our createCourse event as well, and that way, every time any reaction is made, this will automatically update. So what we can do now is create a delete method and see if that automatically updates.
Deleting Data with DELETE Requests
We'll create a function in here called deleteCourse, and this will be an async function that will have an ID passed to it. And this ID we'll pass into Axios to use for our response. We'll run let data = await api.delete, and for this delete function, we're going to pass in the variable of the ID, so we'll do ${id} in here, and that should work. Now all we have to do is create a button to execute this function, so let's create a button here in our map, and we'll just do an 'X'. We'll run onClick and we'll pass a function in here that will run this.deleteCourse and pass in the course.id. Let's save that, and finally, we'll also run the function this.getCourses so we can see if it's been updated when we delete it. So now we can delete a course, and we can create a course. And that seems to be working very well with Axios.
Updating Data with PATCH Requests
We might also want to be able to update some of the data in our API, and we can do this by calling a patch request. Let's create a new function to see how that works. We'll create updateCourse, and this will be an async function which will pass an ID and maybe even a value over in this case. Now in this case, what we're going to do is just update the title of the course. So what we're going to do is create a let data = await api... and this will be patch. In here we're going to pass in the ID that we want to reference. So in this case the ID is going to be the ID we call in our async function, and we're going to pass in the new data that we want. In this case, we just want to update the title to be the value that we've set across. So we'll run this, and then we'll run this.getCourses.
Now finally, what we're going to do is create something very simple where if you select the course, it adds a letter 'A' to the end of it. So we're just going to do an onClick handler here for the <h2> tag, and what we'll do is call in the same sort of function we did for our delete, but in this case, we're going to call updateCourse. What we'll do is we'll pass in the course ID, which is over here, course.id, and we'll pass in the same course name that we had previously but add another letter to it. So over here, we'll do course.title and just add the letter 'A' to the end. Let's save that and click on one of our courses, and we can see that the letter A is appearing. If we refresh, it stays consistent because it's already been updated in our REST API.
Implementing Robust Error Handling
API requests aren't always perfect. So if you're using async functions, it's really good to be able to do try...catch loops. So let's set some of these in here. Let's create a try...catch loop here with an error handler and console.log out the error in case it happens. This way, in case our API endpoint can't be accessed, we can make sure that we find out what's causing the issue, and that way we don't have any errors that will cause our application to crash.
Alternatively, you can actually pull this request in with a .catch directly inside. So if an error happens, you can console.log it out or do other actions as well. And this is useful in case you're not even using async functions.
Advanced Axios Configurations
If you have multiple APIs, Axios can be used without setting an instance, and let's give that a shot. Over here, we can do a let data = await and just call axios directly. We can pass in the method, and in this case, will just be a 'get'. We can also pass in the URL, and this URL can be the same that we set previously, but this will give us an example of how it works. And finally, we can pull the data out and apply the same function with the same results.
Sometimes you might want to implement things like unlimited scroll or pass variables in your get requests, and we can do this with Axios as well. In here, we can actually pass some parameters. So let's create an object for that. And with that, maybe we'll just set a limit, and for this limit, maybe we only want to show three courses. So let's apply that and refresh, and we can see that's been working. So if we create a new course, we can't see that happening because we're only limited to the first three. We can add other things in here, such as, for example, putting in where we start. So let's do start on maybe object two. And if we refresh now, you can see that we're starting on the second object, and we're getting the last two here, which is the JavaScript and the test course. If we delete this and refresh, then we're going to only get the last one in there. But if we start at zero and refresh, we get all three. So this is a way you can use parameters to make sure that you're passing in the get request. Of course, you could always manually put in here with a question mark, but this is more friendly and allows you to pass those attributes in a lot easier.
Sometimes you might also be accessing API endpoints that require you to use a token or a key, and Axios makes this easy as well. You can create headers here by just passing in headers to the initializer and create anything you want, such as X-Auth-Key. In here we can pass in a token key that's maybe 'token123'. Now this can be reset when a user logs off, or it can be generated when they log in, and all your requests using the API key over here will be added to your requests, whether they're gets or puts, and make sure that the user is properly authenticated.
Conclusion and Next Steps
I hope this video gave you a good idea of what it's like to use React and Axios together. Obviously, there's a lot more to it, and you can do a lot of things like adding it to a store, maybe even just using it as a once-off in plain JavaScript, and using it in a Node.js application. We might take a look at some of those examples in another video. Otherwise, if you like this kind of content and you want to see more like it, hit a like and subscribe, and I'll see you next time. Thanks.