Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make ajax call in ReactJS

Introduction to AJAX and ReactJS

Before we dive into the main topic, let's get a basic idea about AJAX and ReactJS. AJAX, which stands for Asynchronous JavaScript and XML, allows us to update a web page without reloading the entire page. It's like a waiter in a restaurant who collects your orders and brings your food without needing you to move or the restaurant to close.

ReactJS, on the other hand, is a JavaScript library for building user interfaces. Think of it as Lego blocks. Each block (component in React) can be used to build a variety of structures (web pages or applications) without having to create each structure from scratch.

Setting up the React Environment

Assuming you have Node.js and npm installed on your machine, create a new React application using the command npx create-react-app ajax-in-react. This might take a few minutes as it sets up the environment and installs the necessary packages. Once it's done, navigate into the project folder using cd ajax-in-react.

What is an API?

To demonstrate an AJAX call, we'll need a server to respond to our request. For this, we'll use a placeholder API. An API, or Application Programming Interface, is like a menu in a restaurant. It tells you what you can order (or request), and the kitchen (server) will prepare and return what you asked for.

Making an AJAX Call in React

In React, we typically make AJAX calls in the lifecycle method componentDidMount(). This method runs after the component output has been rendered to the DOM, which is like saying "after the restaurant has been built and is open for business".

Here's a basic example:

import React, { Component } from 'react';

class App extends Component {
  componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
  }

  render() {
    return (
      <div className="App">
        <h1>Check the console for data</h1>
      </div>
    );
  }
}

export default App;

In this code, we're using the fetch() function to make an AJAX call to the JSON Placeholder API. fetch() returns a promise that resolves to the Response object representing the response to the request. This Response object is then converted to JSON, and we're logging the resulting data to the console.

Displaying Data from an AJAX Call

Logging data to the console isn't very useful in a real-world application, so let's display it on the page. We'll store the data in the component's state and display it in the render() method. Here's how to do it:

import React, { Component } from 'react';

class App extends Component {
  state = {
    post: null
  };

  componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(data =>
        this.setState({
          post: data
        })
      )
      .catch(error => console.error(error));
  }

  render() {
    const { post } = this.state;

    return (
      <div className="App">
        {post ? (
          <div>
            <h1>{post.title}</h1>
            <p>{post.body}</p>
          </div>
        ) : (
          <p>Loading...</p>
        )}
      </div>
    );
  }
}

export default App;

In this code, we're setting the state of post to the data we get from the AJAX call in componentDidMount(). In the render() method, we're checking if post is not null. If it is, we display a loading message; if not, we display the post title and body.

Conclusion

By now, you should have a basic understanding of how to make AJAX calls in React. This is a fundamental part of working with React, and it opens the door to working with APIs and creating dynamic, data-driven applications. There's a lot more to learn, but this should give you a solid foundation to build on. Happy coding!