AJAX (Asynchronous JavaScript and XML) is a technique used in web development to send and receive data from a server asynchronously, without requiring a full page reload. It enables us to create dynamic and interactive web applications by allowing data to be exchanged with the server in the background, without disrupting the user experience.
There are many ways to make AJAX requests in ReactJS. We will explore how to make AJAX requests in ReactJS using Axios.
Axios is a JavaScript library that is often used to make HTTP calls. It has an API that is easy to use and supports modern browsers. Run the following code in the root directory of your project to set up Axios.
npm install axios
In the component file where you want to make the AJAX request, import Axios at the top.
import axios from 'axios';
Define a function within your component that will handle the AJAX request. This function can be triggered by a button click, form submission, or any other event in your application.
import React from 'react';import axios from 'axios';function MyComponent() {const handleRequest = () => {axios.get('https://jsonplaceholder.typicode.com/posts').then(response => {const formattedData = response.data.map(post => ({id: post.id,userId: post.userId,title: post.title,body: post.body,}));setPosts(formattedData);}).catch(error => {console.error(error);// Perform custom error handling, show error message, etc.});};};return (<div><button onClick={handleRequest}>Make AJAX Request</button></div>);}export default MyComponent;
You have to send a GET request to the given URL with the help of the axios.get()
method. When the server responds successfully, the .then()
code is called. This will let you handle the data the server sends back.
In case, the AJAX request encounters an error, the .catch()
function is called, providing you an opportunity to handle and log the error. In the code above, the error info is being written to the console.
.App { text-align: center; } .App-logo { height: 40vmin; pointer-events: none; } @media (prefers-reduced-motion: no-preference) { .App-logo { animation: App-logo-spin infinite 20s linear; } } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } @keyframes App-logo-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
Lines 7–9: The useEffect
hook is used to fetch data when the component mounts, by calling the fetchData
function.
Lines 11–26: The fetchData
function is defined, which makes an AJAX request using the axios library to retrieve data from the specified API endpoint.
Lines 14–19: The response data is formatted and stored in the formattedData
variable as an array of objects with specific properties (id, userId, title, body).
Line 20: The setPosts
function is used to update the posts
state variable with the formatted data.
Lines 31–54: The rendered JSX includes a heading and a conditional statement to check if the posts
array has any data. If posts
contains data, a table is rendered using JSX. The table header and body are generated using the map
function on the posts
array and rendering each post's data in the table cells. If posts
is empty, a paragraph saying "no data available" is rendered instead.
We looked at how to use the Axios library to make AJAX calls in ReactJS. By following the steps given, you can easily add AJAX features to your React apps, which will allow them to talk to servers and get data without waiting. ReactJS makes it easy to handle AJAX calls, which are an important part of making dynamic and responsive web apps.
Free Resources