Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get axios.get response data in ReactJS

Getting Started with Axios

Axios, in simple terms, is a popular, promise-based HTTP client that is used to make HTTP requests from the browser to the server. It's like a messenger that runs back and forth between your application (the client) and the server, carrying messages (data).

Imagine running a restaurant (your application). Your waiters (Axios) take orders (requests) from customers (your application's users), bring them to the kitchen (the server), and then bring back meals (data) from the kitchen to the customers.

In this blog, we will focus on one specific type of order: the GET request, which is like a customer asking for a menu. The waiter goes to the kitchen and comes back with the menu (data).

Installing Axios

First things first, we need to hire our waiter. In code terms, we need to install Axios in our project. We can do this by using npm (node package manager), a tool that helps us manage and install packages like Axios in our project.

Open your terminal and navigate to your project's directory, then type:

npm install axios

Once Axios is installed, we can import it into our project file where we want to use it. For instance:

import axios from 'axios';

Making a GET Request with Axios

Now, let's make our first GET request to fetch some data.

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data', error);
  });

In the above code snippet, we're asking Axios to get data from the provided URL (https://api.example.com/data). Once Axios gets the data, it returns a promise (like a receipt that our order will be fulfilled). We then use .then to handle the data when it arrives, and .catch to handle any errors that might occur during the request.

Understanding the Response Object

The response object returned by Axios has several properties that may be useful. However, the one we are most interested in for this blog post is response.data, which contains the actual data returned from the server.

Think of response as a complete meal served at a restaurant. It consists of several items (properties), but the main course (response.data) is what we're really there for!

Using Axios with ReactJS

Let's now see how we can use Axios in a React component to fetch and display data.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const DataComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data', error);
      });
  }, []);

  return (
    <div>
      {data && data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </div>
  );
}

export default DataComponent;

In this component, we're using the useState hook to create a state variable data where we'll store our fetched data. The useEffect hook is used to fetch the data when the component mounts (when it's first displayed on the screen). We then set the fetched data to the data state variable. In the return statement, we map over data and display each item's name.

Conclusion

Imagine trying to run a restaurant without a waiter or trying to fetch data without a tool like Axios — sounds pretty chaotic, right? Axios acts as a reliable link between the front end and the backend, ensuring the smooth flow of data.

Learning how to fetch data is a crucial skill in web development. However, remember that each application is different. The examples provided might not work perfectly in your case. You might need to tweak them a bit based on your application's needs.

But now that you understand the basics of how to get data using Axios in React, you're well on your way to becoming a master chef in the kitchen of web development!