2.2.1: AJAX
Learning Objectives
AJAX means asynchronous HTTP requests in JavaScript that can update UI without refreshing the page
We can send arbitrary HTTP requests from any React component to send and retrieve data from external APIs
Understand how to send HTTP requests from React components and where to send them
Introduction
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.
The examples fetch first-load data in
componentDidMount
oruseEffect
instead of inrender
or directly in the functional component to avoid fetching data every time the component re-rendersres.json()
extracts the JSON object out of the response.result
in the subsequent callback contains that object.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