What is Axios and how to use it with React 🚀

What is Axios and how to use it with React 🚀

Image for postPhoto by Emile Perron on Unsplash

Working in web development is interesting and many times quite challenging.

We must integrate our applications with many external services. Most probably one of the things you must do when working on a frontend application is calling a backend service to fetch some data (by sending an HTTP request).

Axios, being an HTTP client library, helps you with just that: sending HTTP requests and managing the responses ?.

A little bit of history ?

In the beginning of times (well, actually, in the beginning of web development) there was only the synchronous request-response model.

Whenever you accessed a link (a URL), an HTTP request was sent to the server (via your browser), which returned an HTML document with all the content that the user would see, until he/she navigated to another web page.

That?s it. There was no updating the web-page in the middle of user-interaction, or fetching some data from the server without reloading the page or navigating to another one.

Then, XMLHttpRequest was born ?.

AJAX

AJAX stands for Asynchronous Javascript and XML. Nowadays it is a common practice, but back in the day it was something fresh and cool ?.

Basically, AJAX is a programming technique where the content of a web page is updated asynchronously without the need to reload it.

XMLHttpRequest was the technology which let AJAX thrive. By using this great new feature, you could call the servers to fetch or send data from the frontend (using Javascript), and dynamically update the content of the page. Wow, welcome smooth interaction! ?

With XMLHttpRequest all kinds of resources can be fetched, it doesn?t have to be XML! (Hi there, JSON)

?The? fetch

XMLHttpRequest went a long way, and it is still relevant.

However, for most use cases, it is too complicated and cumbersome to work with. This is why fetch was born.

Fetch (another browser API) let?s you send HTTP requests and handle them by using Promises (a more modern approach to work with asynchronous behaviour).

Present days ?

Nowadays, in most of the cases starting off with fetch is just fine.

However, for a more complete and mature management of HTTP requests, using another Javascript library is recommended but also common practice.

Please welcome Axios! ?

Axios basic APIs

Axios provides a really simple API for getting started with HTTP requests.

In the above example, you can see an HTTP GET request being sent (usually used to? get/ask for data from the server) and then an HTTP POST request, with a request body describing the doggie ? we?d like to create (by using a simple Javascript object that is going to be serialised into a JSON object).

Axios assumes that the communication between the client and server is in JSON format (request and response bodies). This can be changed, but it is safe to assume that JSON is what you want in 99.9% of the cases.

Making it work with React

Enough talk! Let?s take a look at a React app that makes use of Axios for fetching and submitting some data.

Image for postThe app we?ll build ? DoggieManager ?

We?re going to look at a simple React application that let?s us visualise and add a new dog.

You can find the project on GitHub right here.

Installing Axios

After you bootstrap your React application (by using Create React App, Next.js or whatever?s your preference), you can easily add the Axios library using your favourite package manager ? I?m using npm here:

npm install ?-save axios

This will install Axios in your node_modulesfolder and also add it to the package.jsonso it is listed as a dependency of your app.

Cool! Now we?re ready to use it.

Making a simple GET and POST request

In our DoggieManager application, we are querying the dogs list from the server and showing it in the DogManager functional React component.

DogManager is a simple component that receives the list of the dogs via a prop and also receives a prop callback function that it will call whenever a user want to create a new doggie.

This component does not make any Axios calls in itself. We are trying to do a little bit of an abstraction here and put the actual network calls in the parent component, App.js.

The loadDogs function (line 12) calls the Axios API which sends a GET request to our dogs? URL. Afterwards, it sets the internal component state?s dog list with the result of the HTTP request, which in turn is passed down to the DogManager as a prop. Nice! ?

The useCallback React hook is used here as we want to memoize the loadDogs function and not recreate it with every render.

On line 23 of App.js we are defining a function that will kick off our Axios POST request in order to send the new dog?s name to the server. Let?s see that code again:

By using the Axios API we?re telling Axios to send an HTTP POST request to the ${myDogServerBaseURL}/dogs URL with the name in the request body.

After that, we?re setting up the Promise handlers: then for a successful request and catch for a failed one.

If the request went through and everything?s fine (the then handler), we reload our dogs? list. In case of a failure (catch handler), we analyse the HTTP status code returned by the server. Should it be 409 ? Conflict, we know that a doggie with the same name is already in our list.

Note: In this example, let?s presume the frontend and the backend have some kind of an interface contract between them (an API documentation of some sorts), thus we know what status code 409 means in our DogManager?s context.

Great! Now we?ve seen how a simple request and response handling looks like! ?

Using async/await

In all of our above examples we used Promises to handle the asynchronous HTTP responses.

Let?s see how we can make use of async/await to make our code (maybe) a little bit more concise and readable.

Also, you can check out the async-await branch on the DoggieManager project?s GitHub page.

All right, let?s get rid of some callbacks!

Here?s the loadDogs function rewritten with async-await:

As you can see we?re waiting for the request to finish and then work with the result.

Okay, but what about a situation with an error? Let?s rewrite the function that adds a new doggie:

Here we are handling an unsuccessful request as well (whenever the HTTP response status code is not in the 2xx territory).

Using async-await within this scenario is also really straight-forward. We catch the error via try-catch and proceed the same way as before ?.

Configuring Axios

Axios is also dead easy to configure.

You most likely don?t want to retype every time the base URL you are making requests to. No problem, Axios has got you covered. You can set the base URL easily either globally, or by creating an Axios ?instance?.

Want to set a header for every request? This comes in handy when you must send an Authorization header for your oAuth scheme/ security.

Other cool Axios facts

It is also worth knowing about the following functionalities of this neat little library:

  1. Hey, it also works on the server-side! Yup, no need for a browser environment. Thus, you can use Axios in your Node apps as well.
  2. Axios has the functionality of interceptors. You can intercept your requests before them being handled by your callbacks (then/ catch). In case of a session expiration, want to always redirect the user to the login page if you get a 440-Login Time-out HTTP status code back? Easy, set an interceptor ?.
  3. Monitoring upload and download progress is easy, just set a callback in the request config:

4. Cancelation of requests is possible! Great for handling of quick things like live server-querying for search fields.

In closing

Thank you for reading this article all the way through! You rock ?.

Go ahead and try Axios out if you haven?t already, it will make your life easier and also grow you professionally as a developer.

Cheers!

JavaScript In Plain English

Enjoyed this article? If so, get more similar content by subscribing to our YouTube channel!

12

No Responses

Write a response