Why use Axios? – The Ultimate Ajax Library

Today’s tutorial is to help those ES5 migrants to understand why people are flocking to Axios.js for their Web API call needs. To start, this tutorial ES5 styled of coding to demonstrate usage of Axios web call. It is almost the same in ES 6.0 except you would use import and arrow function instead.

So, in short, what’s so good about Axios? To me, I see two advantages.

  • Backward compatibility support, as stated Axios is Promise-based HttpClient , if you read my previous post in here, you will soon notice Promise function is not supported by IE 11 and some variant of Opera Browser.
  • Has a graceful timeout handling – timeout is always a tricky subject when it comes to jQuery bunch and even those using Fetch() in ReactJS too.
  • Simplify your development code, especially when you need to combine Ajax with Promise.all

Without further adieu, let’s bang some codes!

The html template with some bootstrap css.

<html>
    <head>
        <title>Axios Demo</title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
        <style>
            * {
                font-family: 'Roboto', sans-serif;
            }
        </style>
        <script crossorigin="anonymous" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    </head>
    <body>
        <div class="container p-2">
            <h1>Axios Sample</h1>
            <p>This is a sample tutorial on how to write an ajax call with a graceful timeout using Axios.</p>
            <p>
                <div class="form-group">
                    <label for="txtMilisecond">Timeout in Milisecond (lessen the amount to test timeout handling)</label>
                    <input class="form-control" id="txtMilisecond" placeholder="Enter milisecond" type="number" value="2000">
                </div>
            </p>
            <p>
                <kbd>Refer to console after clicking on the button...</kbd>
            </p>
            <p>
                <div class="alert alert-danger d-none" id="alertFail" role="alert">
                    Ohh..uh...Time out already!
                </div>
                <div class="alert alert-success d-none" id="alertSuccess" role="alert">
                    Data loaded, check console!
                </div>
            </p>
            <button class="btn btn-secondary d-none" id="btnSpinner" role="button">
                <span aria-hidden="true" class="spinner-border spinner-border-sm" role="status"></span>
            </button>
            <button class="btn btn-primary" id="btnClickMe" role="button">Click Me to Call</button>
        </div>
    </body>
</html>

In the template above, I import a unpkg version axios so that it can work in default vanilla es5 js environment. A button with the id btnClickMe, will trigger my function to call Axios taking in the values of the input box above with the id of txtMilisecond. Expected outcome of this tutorial will be like the image below.

Next, let’s add in the script.

<html>
    <head>
        <title>Axios Demo</title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
        <style>
            * {
                font-family: 'Roboto', sans-serif;
            }
        </style>
        <script crossorigin="anonymous" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    </head>
    <body>
        <div class="container p-2">
            <h1>Axios Sample</h1>
            <p>This is a sample tutorial on how to write an ajax call with a graceful timeout using Axios.</p>
            <p>
                <div class="form-group">
                    <label for="txtMilisecond">Timeout in Milisecond (lessen the amount to test timeout handling)</label>
                    <input class="form-control" id="txtMilisecond" placeholder="Enter milisecond" type="number" value="2000">
                </div>
            </p>
            <p>
                <kbd>Refer to console after clicking on the button...</kbd>
            </p>
            <p>
                <div class="alert alert-danger d-none" id="alertFail" role="alert">
                    Ohh..uh...Time out already!
                </div>
                <div class="alert alert-success d-none" id="alertSuccess" role="alert">
                    Data loaded, check console!
                </div>
            </p>
            <button class="btn btn-secondary d-none" id="btnSpinner" role="button">
                <span aria-hidden="true" class="spinner-border spinner-border-sm" role="status"></span>
            </button>
            <button class="btn btn-primary" id="btnClickMe" role="button">Click Me to Call</button>
        </div>
        <script>
            $("#btnClickMe").on("click", function (evt) {
                myAxiosWebCallFunction();
                $("#alertSuccess").addClass("d-none");
                $("#alertFail").addClass("d-none");
                $("#btnSpinner").removeClass("d-none");

            });

            function myAxiosWebCallFunction() {
                var someAPIURL = "https://script.google.com/macros/s/AKfycbyWx63L82e2DqT50ILpYL6rpGXakBaRteP-gzqdg-tnI1-xTEs/exec";
                var timeOutInMiliseconds = ($("#txtMilisecond").val() != "") ? $("#txtMilisecond").val() : 2000;

                var request = axios.get(someAPIURL, {timeout: timeOutInMiliseconds});
                request.then(function (result) {
                    console.log(result.data);
                    $("#alertSuccess").removeClass("d-none");
                    $("#btnSpinner").addClass("d-none");
                });
                request.catch(function (error) {
                    console.log("Some error occurred", error);
                    $("#alertFail").removeClass("d-none");
                    $("#btnSpinner").addClass("d-none");
                });
            }
        </script>
    </body>
</html>

Lastly, check out how Axios reduced the need to even use Promise and meshes around our ajax call. Compare with the code I have here

axios.all([
  axios.get('https://api.github.com/users/testurl1'), 
  axios.get('https://api.github.com/users/testurl2')
])
.then(axios.spread((obj1, obj2) => {
  // Both requests are now complete
  console.log(obj1.data.login + ' has ' + obj1.data.public_repos + ' public repos on GitHub');
  console.log(obj2.data.login + ' has ' + obj2.data.public_repos + ' public repos on GitHub');
}));

That’s it for today folks. Hope you enjoy this tutorial.


Comments

comments