How to Fetch API Data in React with JavaScript Fetch and Axios

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

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

This lesson preview is part of the Beginner's Guide to Real World React course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to Beginner's Guide to Real World React, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Beginner's Guide to Real World React
  • [00:00 - 00:39] Welcome to module 4, 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 front end application where React is employed this will most likely be via an API. Chewing this module will be looking at different ways you can retrieve data from an external API and handle a response using the Axios HTTP client package. As we've previously discussed React is quite unappininated 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 seen this unappininated nature leaves us with some gaps. Unlike its fellow front end framework Angular for example.

    [00:40 - 01:27] 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 because connecting to an API isn't particularly difficult but it does mean we have to make some decisions around how we do this . How to handle errors and creating some sort of library or utility class to wrap this all up in. Or we can use a third party package such as Axios which we'll be discussing in a moment. Since you're faced with rolling your own solution to access APIs in React you 'll likely encounter one of these three most common solutions. Using an XML HTTP request to implement an Ajax call, using JavaScript native fetch API or 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.

    [01:28 - 01:51] When it comes to asynchronous data loading network requests, Ajax is at the forefront. It stands for asynchronous JavaScript in XML and is a combination of the built in XML HTTP request object which goes off to the server to retrieve the data and JavaScript in the DOM to use the data. Add its call is the XML HTTP request object and this is the means that you would use to fetch the data. An example implementation might look like this.

    [01:52 - 03:21] So assuming we have an element on the page called output, this snippet prepares a new XML HTTP request and opens the connection to free core API service. When the state changes and is successful, i.e. a ready state of four, we parse the response text object which represents the response data as a string. You won't see as many direct implementations of the XML HTTP request object in a lot of code bases today. Whilst perfectly legal and legitimate code, it is considered a little outdated by modern replacements like the fetch API. Although it has support for older browsers, especially Internet Explorer, the XML HTTP request is a more complicated way to handle async network requests. It doesn't support promise object chaining very well and requires a number of wrapper functions to get the best from it. 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 XML HTTP request 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-aware syntax. The downsides to the fetch API are, pull support for older browsers, with zero support for any version of Internet Explorer. Typical errors are not rejected, with this can lead to false positives when expecting to catch errors like 500 or 404, and timeouts and progress reports are not supported, meaning the 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.

    [03:22 - 03:55] As you can see, much more readable and clear and much easier to implement. Now 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 wear those up and make the decision. However, there are times when employing a well-maint ained and supported package makes good sense. For situations with complex requirements such as support in different environments, browsers, error handling, using callbacks and everything in between, sometimes it just makes sense to lean on an existing and robust solution.

    [03:56 - 04:36] 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 XML HTTP request 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's main benefits over the previous two options include support for both browser and node development, support for older browsers, it implements interceptors for requests and responses, this is handy if you're using authentication tokens for example. Automatic transformation of request and response data, client side protection against cross-site request forgery and support for progress reports.

    [04:37 - 05:05] Big and NPM package, you would add it to your project in the same way as any other package using the command 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 the concise article from Plural site, link to in the course notes. In the next lesson, we'll be implementing Axios to build our furry friends gallery idea from the last module.