React Axios example – Get/Post/Put/Delete with Rest API

Axios is a promise-based HTTP Client Javascript library for Node.js and Browser. In this tutorial, we will create React example that use Axios to make Get/Post/Put/Delete request with Rest API and JSON data in a React functional component (with Hooks).

Related Posts:
React Custom Hook
Axios Tutorial: Get/Post/Put/Delete request example
React CRUD example with Axios, React Router and Rest API
React Hooks: JWT Authentication & Authorization (without Redux) example
React Hooks + Redux: JWT Authentication & Authorization example

Together with React Query:
React Query and Axios example with Rest API


React Axios example Overview

We will build a React Client with Axios library to make CRUD requests to Rest API in that:

  • React Axios GET request: get all Tutorials, get Tutorial by Id, find Tutorial by title
  • React Axios POST request: create new Tutorial
  • React Axios PUT request: update an existing Tutorial
  • React Axios DELETE request: delete a Tutorial, delete all Tutorials

react-axios-example

This React Axios Client works with the following Web API:

Methods Urls Actions
POST /api/tutorials create new Tutorial
GET /api/tutorials retrieve all Tutorials
GET /api/tutorials/:id retrieve a Tutorial by :id
PUT /api/tutorials/:id update a Tutorial by :id
DELETE /api/tutorials/:id delete a Tutorial by :id
DELETE /api/tutorials delete all Tutorials
GET /api/tutorials?title=[keyword] find all Tutorials which title contains keyword

You can find step by step to build a Server like this in one of these posts:

Remember that you need to configure CORS: Access-Control-Allow-Origin: *.
It helps the REST APIs can be accessed by any origin.

How to import Axios in React

There are 2 ways to import Axios into React Application:

Using CDN:

  • jsDelivr CDN:
  • <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  • unpkg CDN:
  • <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    

For example, open public/index.html and add HTML <script> element into <head> tag:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta
      name="description"
      content="React Axios example - GET/Post/Put/Delete"
    />
    ...
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <title>React Axios example</title>
  </head>
  <body>
    ...
  </body>
</html>

– Installing axios module:

Create Axios instance in React

We can create a new instance of axios using axios.create(config) method, then export it as an apiClient:

src/http-common.js

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:8080/api",
  headers: {
    "Content-type": "application/json"
  }
});

In src/App.js

import apiClient from "./http-common";
...

Now we can use apiClient to send HTTP requests and receive responses.

The response for a Axios request contains:

  • data: parsed response body provided by the server
  • status: HTTP status code
  • statusText: HTTP status message
  • headers: HTTP headers (lower case)
  • config: the request config that was provided to axios
  • request: the last client request instance that generated this response
For more details about Axios (with instance creation, params, json, body, headers, error handling…), kindly visit:
Axios Tutorial: Get/Post/Put/Delete request example

React Axios Get JSON data

Let’s implement a React component to fetch JSON data from API:

  • get all Tutorials
  • get Tutorial by Id
  • find Tutorial by title
import React, { useRef, useState } from "react";
import "./App.css";

import apiClient from "./http-common";

function App() {
  const get_id = useRef(null);
  const get_title = useRef(null);

  const [getResult, setGetResult] = useState(null);

  const fortmatResponse = (res) => {
    return JSON.stringify(res, null, 2);
  };

  async function getAllData() {
    try {
      const res = await apiClient.get("/tutorials");

      const result = {
        status: res.status + "-" + res.statusText,
        headers: res.headers,
        data: res.data,
      };

      setGetResult(fortmatResponse(result));
    } catch (err) {
      setGetResult(fortmatResponse(err.response?.data || err));
    }
  }

  async function getDataById() {
    const id = get_id.current.value;

    if (id) {
      try {
        const res = await apiClient.get(`/tutorials/${id}`);

        const result = {
          data: res.data,
          status: res.status,
          statusText: res.statusText,
          headers: res.headers,
        };

        setGetResult(fortmatResponse(result));
      } catch (err) {
        setGetResult(fortmatResponse(err.response?.data || err));
      }
    }
  }

  async function getDataByTitle() {
    const title = get_title.current.value;

    if (title) {
      try {
        // const res = await instance.get(`/tutorials?title=${title}`);
        const res = await apiClient.get("/tutorials", {
          params: {
            title: title,
          },
        });

        const result = {
          status: res.status + "-" + res.statusText,
          headers: res.headers,
          data: res.data,
        };

        setGetResult(fortmatResponse(result));
      } catch (err) {
        setGetResult(fortmatResponse(err.response?.data || err));
      }
    }
  }

  const clearGetOutput = () => {
    setGetResult(null);
  };

  return (
    <div id="app" className="container">
      <div className="card">
        <div className="card-header">React Axios GET - BezKoder.com</div>
        <div className="card-body">
          <div className="input-group input-group-sm">
            <button className="btn btn-sm btn-primary" onClick={getAllData}>Get All</button>

            <input type="text" ref={get_id} className="form-control ml-2" placeholder="Id" />
            <div className="input-group-append">
              <button className="btn btn-sm btn-primary" onClick={getDataById}>Get by Id</button>
            </div>

            <input type="text" ref={get_title} className="form-control ml-2" placeholder="Title" />
            <div className="input-group-append">
              <button className="btn btn-sm btn-primary" onClick={getDataByTitle}>Find By Title</button>
            </div>

            <button className="btn btn-sm btn-warning ml-2" onClick={clearGetOutput}>Clear</button>
          </div>   
          
          { getResult && <div className="alert alert-secondary mt-2" role="alert"><pre>{getResult}</pre></div> }
        </div>
      </div>
    </div>
  );
}

export default App;

The result will look like this:

react-axios-get-json-data

Find tutorial by id:

react-axios-get-json-data-search

Filter tutorials by title:

react-axios-get-json-data-filter

React Axios Post

Let’s use React Axios POST Json data to create new Tutorial.

To send the request with Headers, we pass an option object with headers property right after the body.

import React, { useRef, useState } from "react";
import "./App.css";

import apiClient from "./http-common";

function App() {
  const post_title = useRef(null);
  const post_description = useRef(null);

  const [postResult, setPostResult] = useState(null);

  const fortmatResponse = (res) => {
    return JSON.stringify(res, null, 2);
  };

  async function postData() {
    const postData = {
      title: post_title.current.value,
      description: post_description.current.value,
    };

    try {
      const res = await apiClient.post("/tutorials", postData, {
        headers: {
          "x-access-token": "token-value",
        },
      });

      const result = {
        status: res.status + "-" + res.statusText,
        headers: res.headers,
        data: res.data,
      };

      setPostResult(fortmatResponse(result));
    } catch (err) {
      setPostResult(fortmatResponse(err.response?.data || err));
    }
  }

  const clearPostOutput = () => {
    setPostResult(null);
  };

  return (
    <div id="app" className="container">
      <div className="card">
        <div className="card-header">React Axios POST - BezKoder.com</div>
        <div className="card-body">
          <div className="form-group">
            <input type="text" className="form-control" ref={post_title} placeholder="Title" />
          </div>
          <div className="form-group">
            <input type="text" className="form-control" ref={post_description} placeholder="Description" />
          </div>
          <button className="btn btn-sm btn-primary" onClick={postData}>Post Data</button>
          <button className="btn btn-sm btn-warning ml-2" onClick={clearPostOutput}>Clear</button>

          { postResult && <div className="alert alert-secondary mt-2" role="alert"><pre>{postResult}</pre></div> }
        </div>
      </div>
    </div>
  );
}

export default App;

Check the result by making a React Axios Post Request:

react-axios-post-example

React Axios Put

We’re gonna use React with Axios PUT request to update an existing Tutorial.

import React, { useRef, useState } from "react";
import "./App.css";

import apiClient from "./http-common";

function App() {
  const put_id = useRef(null);
  const put_title = useRef(null);
  const put_description = useRef(null);
  const put_published = useRef(null);

  const [putResult, setPutResult] = useState(null);

  const fortmatResponse = (res) => {
    return JSON.stringify(res, null, 2);
  };

  async function putData() {
    const id = put_id.current.value;

    if (id) {
      const putData = {
        title: put_title.current.value,
        description: put_description.current.value,
        published: put_published.current.checked,
      };

      try {
        const res = await apiClient.put(`/tutorials/${id}`, putData, {
          headers: {
            "x-access-token": "token-value",
          },
        });

        const result = {
          status: res.status + "-" + res.statusText,
          headers: res.headers,
          data: res.data,
        };

        setPutResult(fortmatResponse(result));
      } catch (err) {
        setPutResult(fortmatResponse(err.response?.data || err));
      }
    }
  }

  const clearPutOutput = () => {
    setPutResult(null);
  };

  return (
    <div id="app" className="container">
      <div className="card">
        <div className="card-header">React Axios PUT - BezKoder.com</div>
        <div className="card-body">
          <div className="form-group">
            <input type="text" className="form-control" ref={put_id} placeholder="Id" />
          </div>
          <div className="form-group">
            <input type="text" className="form-control" ref={put_title} placeholder="Title" />
          </div>
          <div className="form-group">
            <input type="text" className="form-control" ref={put_description} placeholder="Description" />
          </div>
          <div className="form-check mb-2">
            <input type="checkbox" className="form-check-input" ref={put_published} />
            <label className="form-check-label" htmlFor="put_published">Publish</label>
          </div>
          <button className="btn btn-sm btn-primary" onClick={putData}>Update Data</button>
          <button className="btn btn-sm btn-warning ml-2" onClick={clearPutOutput}>Clear</button>

          { putResult && <div className="alert alert-secondary mt-2" role="alert"><pre>{putResult}</pre></div> }
        </div>
      </div>
    </div>
  );
}

export default App;

The result will look like this:

react-axios-put-example

React Axios Delete

Now we implement a React component to delete data with Axios Delete method:

  • delete a Tutorial
  • delete all Tutorials
import React, { useRef, useState } from "react";
import "./App.css";

import apiClient from "./http-common";

function App() {
  const delete_id = useRef(null);
  
  const [deleteResult, setDeleteResult] = useState(null);

  const fortmatResponse = (res) => {
    return JSON.stringify(res, null, 2);
  };

  async function deleteAllData() {
    try {
      const res = await apiClient.delete("/tutorials");

      const result = {
        status: res.status + "-" + res.statusText,
        headers: res.headers,
        data: res.data,
      };

      setDeleteResult(fortmatResponse(result));
    } catch (err) {
      setDeleteResult(fortmatResponse(err.response?.data || err));
    }
  }

  async function deleteDataById() {
    const id = delete_id.current.value;

    if (id) {
      try {
        const res = await apiClient.delete(`/tutorials/${id}`);

        const result = {
          status: res.status + "-" + res.statusText,
          headers: res.headers,
          data: res.data,
        };

        setDeleteResult(fortmatResponse(result));
      } catch (err) {
        setDeleteResult(fortmatResponse(err.response?.data || err));
      }
    }
  }

  const clearDeleteOutput = () => {
    setDeleteResult(null);
  };

  return (
    <div id="app" className="container">
      <div className="card">
        <div className="card-header">React Axios DELETE - BezKoder.com</div>
        <div className="card-body">
          <div className="input-group input-group-sm">
            <button className="btn btn-sm btn-danger" onClick={deleteAllData}>Delete All</button>

            <input type="text" ref={delete_id} className="form-control ml-2" placeholder="Id" />
            <div className="input-group-append">
              <button className="btn btn-sm btn-danger" onClick={deleteDataById}>Delete by Id</button>
            </div>

            <button className="btn btn-sm btn-warning ml-2" onClick={clearDeleteOutput}>Clear</button>
          </div>    
          
          { deleteResult && <div className="alert alert-secondary mt-2" role="alert"><pre>{deleteResult}</pre></div> }      
        </div>
      </div>
    </div>
  );
}

export default App;

The result could be like this:

react-axios-detete-example

Conclusion

With this React Axios example, you’ve known many ways to make GET/POST/PUT/DELETE request using axios library (with headers, params, body…) in a Reactjs component.

Together with React Query:
React Query and Axios example with Rest API

Instead of Axios, you can also use Javascript Fetch API. Kindly visit:
React Fetch example – Get/Post/Put/Delete with Rest API

Happy Learning! See you again.

Source Code

The complete source code for this tutorial can be found at Github.

Further Reading

5 thoughts to “React Axios example – Get/Post/Put/Delete with Rest API”

Comments are closed to reduce spam. If you have any question, please send me an email.