Introduction to fetching data with React

This lesson introduces the concepts and approaches you can use to deal with fetching data within React, including the JavaScript Fetch API.

Fetching Data#

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.

However, as we’ve also seen, this unopinionated nature leaves us with some gaps. Unlike its fellow frontend framework Angular, for example, which boasts a suite of built-in tools for talking to external sources like APIs, React leaves us with plain old JavaScript.

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:

  1. Using an XMLHttpRequest to implement an AJAX call.

  2. Using JavaScript’s native Fetch API.

  3. 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#

When it comes to asynchronous data loading network requests, AJAX is at the forefront. It stands for Asynchronous JavaScript and XML and is a combination of the built-in XMLHttpRequest object, which goes off to the server to retrieve the data, and JavaScript and the DOM to use the data.

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, 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#

Rightly or wrongly a lot of modern JavaScript development makes use of the extensive npm library of third-party scripts, libraries, and utilities. There are always pros and cons to pulling in another package, and it’s up to you and your development team to weigh those up and make the decision.

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.

No discussions yet