How to fetch data using Axios in React

zubeco

Udeh Princewill Nzubechukwu

Posted on January 1, 2023

How to fetch data using Axios in React

I'm sure almost all Frontend developers at some point might encountered have a need to fetch some data from an API to display on the UI, and today i will be teaching you how to do that in a React Application and we will be using a popular Javascript library called Axios.

Axios is a popular library for making HTTP requests in JavaScript. It's often used with React to fetch data from an API and populate a website with the fetched data. Here's a brief tutorial on how to use Axios to fetch data in a React app

  • First, you'll need to install Axios in your React project. You can do this by running the following command in your terminal:

Using npm:

$ npm install axios 
Enter fullscreen mode Exit fullscreen mode

Using yarn:

$ yarn add axios 
Enter fullscreen mode Exit fullscreen mode
  • Next, you'll need to import Axios into your React component. You can do this by adding the following line to the top of your file:
import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode
  • Now you can use Axios to make HTTP requests from your React component. Here's an example of how to fetch data from an API using Axios:
axios.get('https://my-api.com/endpoint')
  .then(response => {
    // handle success
    console.log(response.data);
  })
  .catch(error => {
    // handle error
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode
  • In the example above, we're using the GET method to send a GET request to the specified endpoint. You can also use Axios to send POST, PUT, and DELETE requests.

  • Once you've received the data from the API, you can use it to update the state of your React component. Here's an example of how to do this:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

  componentDidMount() {
    axios.get('https://my-api.com/endpoint')
      .then(response => {
        this.setState({ data: response.data });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        {this.state.data.map(item => (
          <div key={item.id}>{item.name}</div>
        ))}
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • In the example above, we're using the componentDidMount lifecycle method to make the API request when the component is mounted. The data that we receive from the API is then stored in the component's state, which we can access using this.state.data. Finally, we use the map function to iterate over the data and render a list of items.

I hope this helps! Let me know if you have any questions.

💖 💪 🙅 🚩
zubeco
Udeh Princewill Nzubechukwu

Posted on January 1, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related