Using axios to fetch data in your React apps

Using axios to fetch data in your React apps

Β·

2 min read

In our React applications we often need to retrieve data from external APIs so it can be displayed in our web pages. Axios is designed to handle http requests and responses.

Axios deals with responses using promises, so it's streamlined and easy to use in our code.

Axios uses methods like get() and post() that perform http GET and POST requests for retrieving or creating resources.

Installation

npm install axios

Include in your code

import axios from 'axios';

Basic syntax of a GET request for a resource:

axios.get("http://localhost:3333/items")

We use the get() method and we pass in the URL where the resource lives. Axios does its magic and returns us back a promise. If the promise is successful, it is passes to the then() method where we use it to set the state. If the promise is not successful, we get back an error that is passed to the catch() method where we can display it on the console or in some other fashion.

componentDidMount()
{
  axios.get('http://localhost:3333/items')
  .then(response => this.setState({items:response.data}))
  .catch(err => console.log(err))
}

A complete React component

import React from "react";
import axios from "axios";
class Home extends React.Component{
  state = { users : [] };
  componentDidMount() {
       axios.get("https://jsonplaceholder.typicode.com/users")
       .then((res) => this.setState ({ users : res.data }));
   }
  render(){
      const { users } = this.state;
      const userList=users.length ? (
           users.map(( user ) => {
              return (
                <div key={user.id} >
                   <h2>Name : {user.name}</h2>
                   <h3>Username : {user.username}</h3>
                   <h3>Email : {user.email}</h3>
                   </hr>
                </div>
              );
            })
           )  :  (
                <div>
                   <h1>No Users Registered</h1>
                </div> 
          );
      return <div>{userList}</div>
  }
}

export default Home;

That's itπŸ₯³ You have fetched data in your react app using axios.

Thanks for reading this.πŸ™πŸ»