Introduction to fetching data with React
At some point in the real world, you’re going to have to interact with data from an external source. In a frontend application where React is employed this will most likely be via an API.
During this module, we’ll be looking at different ways you can retrieve data from an external API and handle the response using the Axios HTTP client package.
React’s support for APIs#
As we’ve previously discussed, React is quite unopinionated in its implementation. Outside of a few conventions, such as the JSX syntax and Hooks, it pretty much leaves things up to you to develop how you wish.
This isn’t a huge issue as connecting to an API isn’t particularly difficult, but it does mean we have to make some decisions on how to do this, how to handle errors and creating some sort of library or utility class to wrap this all up in. Or, we could use a third-party package, such as Axios, which we’ll be discussing in a moment.
Data fetching options in React#
Since you’ll be faced with rolling your own solution to access APIs in React, you’ll likely encounter one of these three most common solutions:
XMLHttpRequestto implement an AJAX call.
Adding a third-party library, such as Axios (which is arguably the most popular).
Let’s go over each of these three and discuss their merits and drawbacks.
AJAX calls with XMLHttpRequest#
At its core is the
XMLHttpRequest object and this is the means that you would use to fetch the data.
An example implementation might look like this:
Assuming we have an element on the page called ‘output’ then this snippet prepares a new
XMLHttpRequest and opens the connection to a free quote API service,
https://quotes.rest/qod. When the state changes and it is successful (i.e. a
readyState of 4), we parse the
responseText object which represents the response data as a string.
You won’t see as many direct implementations of the
XMLHttpRequest object in a lot of codebases today. Whilst perfectly ‘legal’ and legitimate code, it’s considered a little outdated by modern replacements like the Fetch API.
Although it has support for older browsers (especially Internet Explorer), the
XMLHttpRequest is a more complicated way to handle async network requests. It doesn’t support Promise changing very well and requires several wrapper functions to get the best from it.
Using the Fetch API#
The more recent approach to handling resource fetching, especially to external APIs, is the built-in Fetch API.
It offers a more straightforward implementation than the previous
XMLHttpRequest option and boasts a more powerful and flexible feature set. Because it employs Promises quite heavily, subsequent action calls can be chained or swapped out for the async/await syntax.
The downsides to the Fetch API are:
Poor support for old browsers (with zero support for any version of Internet Explorer).
Typical errors are not rejected, which can lead to false positives when expecting to catch errors like 500 or 404.
Timeouts and progress reports are not supported, meaning that a request will continue as long as the browser chooses.
If we were to recreate the previous example using the Fetch API, the code would look like this:
As you can see, much more readable and clear and much easier to implement.
Leveraging third-party libraries or packages#
However, there are times where employing a well maintained and supported package makes good sense. For situations with complex requirements, such as supporting different environments, browsers, error handling, using callbacks, and everything in between, sometimes it just makes sense to lean on an existing and robust solution.
This is true when it comes to fetching data from APIs in commercial enterprise codebases. That’s why a package like Axios is so popular. Axios is a wrapper of sorts around the
XMLHttpRequest object, providing much of the same familiar implementation of the Fetch API in the look and feel of how it’s used.
Some of Axios’ main benefits over the previous two options include:
Support for both browser and node development.
Support for older browsers.
Interceptors for requests and responses.
Automatic transformation of request and response data.
Client-side protection against Cross-Site Request Forgery.
Support for progress reports.
Being an npm package, you would add it to your project in the same way as any other package:
yarn add axios
Assuming you have installed axios and imported it into your code, we could achieve the same results as the previous two code examples as follows:
You can read more on the comparisons between Axios and the Fetch API in this concise article from Pluralsight.
In the next lesson, we’ll be implementing Axios to build on our Furry Friends Gallery idea from the last module.