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#
When it comes to asynchronous data loading network requests, AJAX is at the forefront. It stands for Asyn