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 Asyn