2.2.1: AJAX

Learning Objectives

  1. AJAX means asynchronous HTTP requests in JavaScript that can update UI without refreshing the page

  2. We can send arbitrary HTTP requests from any React component to send and retrieve data from external APIs

  3. Understand how to send HTTP requests from React components and where to send them


AJAX (Asynchronous JavaScript and XML) is a technique for sending asynchronous HTTP requests in JavaScript that can update UI without refreshing the page. XML is an older markup language for sending and receiving data that is now less commonly used than JSON, but the software community continues to use the abbreviation AJAX out of convention.

AJAX in React

React's official docs provide clear examples of how to make AJAX requests from both class and Hook-based React components on component load.

  1. The examples use the Fetch AJAX library, but we will use Axios at Rocket because Axios is the most robust and popular as far as we know

  2. The examples fetch first-load data in componentDidMount or useEffect instead of in render or directly in the functional component to avoid fetching data every time the component re-renders

  3. res.json() extracts the JSON object out of the response. result in the subsequent callback contains that object.

  4. The examples show how to send AJAX requests to populate data in components on component load, but not how to send requests on a user action such as a button click (e.g. like button). For the latter we can safely define a callback method in our component (e.g. handleClick) that performs a request on button click without worrying about fetching data more times than necessary.

Axios Implementation of HTTP Request and Response

Please checkout the finished code in this repository, if you want to test out the application on your machine you will need to install the dependencies with the command npm install after the installation you can then run the application with the command npm start, see if you are able to alter the handleSubmit methof to use axios.get instead of fetch.

Last updated