Axios is a very popular promise-based HTTP client. It can help you to efficiently connect your web application with APIs. It has a pretty straightforward syntax and very extensive documentation. Let’s have a look at how to use it in React apps.

To demonstrate axios and its capabilities we’re going to use SWAPI – The Star Wars API. If you want you can familiarise yourself with the full documentation here.

GET request

To install axios in your application you need to run

$ npm install axios

in the root folder of your application. The next step is to import axios in your application.

$ import axios from ‘axios’

And that’s all you need to start making requests. Get request is used to fetch some data from a server. In the code snippet below we have created a simple function called fetchData(). It’s an asynchronous function that uses axios.get() method to ask a given URL for resources.

import axios from "axios";
import { useEffect } from "react";

function App() {
  const fetchData = async () => {
    const { data } = await axios.get("https://swapi.dev/api/people/1");
    console.log(data);
  };
	
  useEffect(() => {
    fetchData();
  }, []);

  return <div></div>;
}
export default App;

In the above example, we’re hitting the SWAPI/people API to get the person with ID = 1. We’re saving the response data object from the API in variable data and proceed to print it out to the console. If you open your developer tools, you should be able to see the following JSON object.

{
  "name": "Luke Skywalker",
  "height": "172",
  "mass": "77",
  "hair_color": "blond",
  "skin_color": "fair",
  "eye_color": "blue",
  "birth_year": "19BBY",
  "gender": "male",
  "homeworld": "https://swapi.dev/api/planets/1/",
  "films": [
    "https://swapi.dev/api/films/1/",
    "https://swapi.dev/api/films/2/",
    "https://swapi.dev/api/films/3/",
    "https://swapi.dev/api/films/6/"
  ],
  "species": [],
  "vehicles": [
    "https://swapi.dev/api/vehicles/14/",
    "https://swapi.dev/api/vehicles/30/"
  ],
  "starships": [
    "https://swapi.dev/api/starships/12/",
    "https://swapi.dev/api/starships/22/"
  ],
  "created": "2014-12-09T13:50:51.644000Z",
  "edited": "2014-12-20T21:17:56.891000Z",
  "url": "https://swapi.dev/api/people/1/"
}

When working with axios you may come across the very common pattern to use the fetcher.js file to store all of your API related functions there and then import them as needed across your application. We can try to apply a similar pattern to our Luke Skywalker example.

Let’s start by creating a fetcher.js in the src folder of our application. We have abstracted out the logic of the application to make the fetchPerson function take an argument of the id of the person that we are interested in. In the context of SWAPI, those are integer values starting at 1.

import axios from "axios";

export const fetchPerson = async (id) => {
  try {
    const { data } = await axios.get(`https://swapi.dev/api/people/${id}`);
    return { status: "success", response: data };
  } catch (error) {
    return { status: "failure", response: error };
  }
};

Now in our App.js we can simply import the new function and start using it immediately.

import { useEffect, useState } from "react";
import { fetchPerson } from "./fetcher";

function App() {
  const [personID, setPersonID] = useState(1);
  const [error, setError] = useState("");
	
  useEffect(() => {
    const fetchData = async () => {
      const { status, response } = await fetchPerson(personID);
      if (status === "success") {
        console.log(response);
      } else if (status === "failure") {
        setError("Failed to fetch data!");
      }
    };
    fetchData();
  }, [personID]);

  return (
    <div>
      <button onClick={() => setPersonID(personID + 1)}>
        Get next person
      </button>
      {error && <p>{error}</p>}
    </div>
  );
}
export default App;

We have initialised a personID and error state that starts at 1 and empty string respectively. personID is incremented by 1 every time we click the ‘Get next person’ button. On every click of the button, the GET request will rerun with the new incremented personID variable, which will fetch us the next person from the Start Wars Universum. In the unlikely event that something goes wrong with the request, we will set the error message to notify the user that something went wrong and we’ll display it on the page.

POST request

POST method is used most commonly to send some data to your server. The server then saves that data, which in most cases can later be retrieved by a GET request.
To demonstrate axios.post() in action we will create a simple form that grabs simple data from users and sends it back to the server for processing.

import axios from "axios";

export const loginUser = async (username, password) => {
  const request = { username: username, password: password };
  try {
    const response = await axios.post("ENDPOINT", request);
    return { status: "success", response: response };
  } catch (error) {
    return { status: "failure", response: error };
  }
};

Above we can see the post method in action. loginUser expects two parameters: username and password. It then creates a request object and assigns those two as properties. We’re then passing the request object as the second argument to the post() method. And that’s it! The client then handles all the rest for us and returns the response object which, we then return.

import { useState } from "react";
import { loginUser } from "./fetcher";

function App() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const handleLogin = async () => {
    const { status, response } = await loginUser(username, password);
    if (status === "success") {
      console.log(response);
    } else if (status === "failure") {
      setError("Something went wrong!");
    }
  };

  return (
    <div>
      <input
        type="text"
        value={username}
        onChange={(event) => setUsername(event.target.value)}
      />
      <input
        type="password"
        value={password}
        onChange={(event) => setPassword(event.target.value)}
      />
      <button onClick={handleLogin}>Login</button>
      {error && <p>{error}</p>}
    </div>
  );
}
export default App;

In App.js we have a very simple application that has two input fields. It saves the provided values in the state of the application. When the user clicks on the Login button the handler gets executed.

Unfortunately given that this is a demo application and that our server endpoint, in reality, doesn’t exist the app will throw an error. Try to find some other public API that will accept POST requests to practice yourself!

Don’t forget to check out the official documentation to explore other methods.

Avatar photo
👋 Hey, I'm Dawid Budaszewski
Hello! I'm Dawid. I'm a full-stack developer with a couple of years of experience under my belt. I spent most of my career working with React. I also built reacterry.com, an online portal with React coding challenges.

💬 Leave a comment

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.