react | fetch / get / post / put / delete / restapi *

https://blog.bitsrc.io/how-to-build-a-contact-form-with-react-js-and-php-d5977c17fec0

https://www.bezkoder.com/react-fetch-example/

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

Last modified: October 26, 2021 bezkoder React

JavaScript Fetch API provides an interface for accessing and manipulating HTTP requests and responses. In this Reactjs tutorial, we will create React Fetch example to make Get/Post/Put/Delete request with Rest API and JSON data.

Related Post:
Javascript Fetch API tutorial: Get/Post/Put/Delete example
React Axios example – Get/Post/Put/Delete with Rest API

 

Contents [hide]

 

React Fetch example Overview

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

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

react-fetch-example

This Fetch 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.

React Fetch data from API example

fetch() returns a Promise that resolves with a Response object, which is fulfilled once the response is available.

const responsePromise = fetch(resourceUrl [, options]);

The Response object we mention above represents the entire HTTP response, it does not directly contain the response body. To get the actual JSON body of the response, we use response.json() method.

We can also access metadata such as headers, status, statusText, type, url from the Response object.

The response Promise does not reject on HTTP errors (for example: 404, 500). It only rejects when encountering a network error. So we need to check for HTTP errors with response.ok status and/or response.status properties.

For more details about fetch() method (with params, json, body, headers, error handling…), kindly visit:
Javascript Fetch API tutorial: Get/Post/Put/Delete example

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";

function App() {
  const baseURL = "http://localhost:8080/api";

  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 fetch(`${baseURL}/tutorials`);

      if (!res.ok) {
        const message = `An error has occured: ${res.status} - ${res.statusText}`;
        throw new Error(message);
      }

      const data = await res.json();

      const result = {
        status: res.status + "-" + res.statusText,
        headers: {
          "Content-Type": res.headers.get("Content-Type"),
          "Content-Length": res.headers.get("Content-Length"),
        },
        length: res.headers.get("Content-Length"),
        data: data,
      };

      setGetResult(fortmatResponse(result));
    } catch (err) {
      setGetResult(err.message);
    }
  }

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

    if (id) {
      try {
        const res = await fetch(`${baseURL}/tutorials/${id}`);

        if (!res.ok) {
          const message = `An error has occured: ${res.status} - ${res.statusText}`;
          throw new Error(message);
        }

        const data = await res.json();

        const result = {
          data: data,
          status: res.status,
          statusText: res.statusText,
          headers: {
            "Content-Type": res.headers.get("Content-Type"),
            "Content-Length": res.headers.get("Content-Length"),
          },
        };

        setGetResult(fortmatResponse(result));
      } catch (err) {
        setGetResult(err.message);
      }
    }
  }

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

    if (title) {
      try {
        // const res = await fetch(`${baseURL}/tutorials?title=${title}`);

        let url = new URL(`${baseURL}/tutorials`);
        const params = { title: title };
        url.search = new URLSearchParams(params);

        const res = await fetch(url);

        if (!res.ok) {
          const message = `An error has occured: ${res.status} - ${res.statusText}`;
          throw new Error(message);
        }

        const data = await res.json();

        const result = {
          status: res.status + "-" + res.statusText,
          headers: {
            "Content-Type": res.headers.get("Content-Type"),
            "Content-Length": res.headers.get("Content-Length"),
          },
          data: data,
        };

        setGetResult(fortmatResponse(result));
      } catch (err) {
        setGetResult(err.message);
      }
    }
  }

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

  return (
    <div className="card">
      <div className="card-header">React Fetch 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>
  );
}

export default App;

The result will look like this:

react-fetch-data-from-api-example

Find tutorial by id:

react-fetch-data-from-api-example-search

Filter tutorials by title:

react-fetch-data-from-api-example-filter

React Fetch POST example

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

We use JSON.stringify() on the object before passing it in the body of the request and set:

  • "post" for method
  • "application/json" for the header Content-Type
import React, { useRef, useState } from "react";

function App() {
  const baseURL = "http://localhost:8080/api";

  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 fetch(`${baseURL}/tutorials`, {
        method: "post",
        headers: {
          "Content-Type": "application/json",
          "x-access-token": "token-value",
        },
        body: JSON.stringify(postData),
      });

      if (!res.ok) {
        const message = `An error has occured: ${res.status} - ${res.statusText}`;
        throw new Error(message);
      }

      const data = await res.json();

      const result = {
        status: res.status + "-" + res.statusText,
        headers: {
          "Content-Type": res.headers.get("Content-Type"),
          "Content-Length": res.headers.get("Content-Length"),
        },
        data: data,
      };

      setPostResult(fortmatResponse(result));
    } catch (err) {
      setPostResult(err.message);
    }
  }
  
  const clearPostOutput = () => {
    setPostResult(null);
  }
  
  return (
    <div className="card">
      <div className="card-header">React Fetch 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>
  );
}

export default App;

Check the result by making a Fetch Post Request:

react-fetch-post-example

React Fetch example – PUT request

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

import React, { useRef, useState } from "react";

function App() {
  const baseURL = "http://localhost:8080/api";

  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 fetch(`${baseURL}/tutorials/${id}`, {
          method: "put",
          headers: {
            "Content-Type": "application/json",
            "x-access-token": "token-value",
          },
          body: JSON.stringify(putData),
        });

        if (!res.ok) {
          const message = `An error has occured: ${res.status} - ${res.statusText}`;
          throw new Error(message);
        }

        const data = await res.json();

        const result = {
          status: res.status + "-" + res.statusText,
          headers: { "Content-Type": res.headers.get("Content-Type") },
          data: data,
        };

        setPutResult(fortmatResponse(result));
      } catch (err) {
        setPutResult(err.message);
      }
    }
  }
  
  const clearPutOutput = () => {
    setPutResult(null);
  }
  
  return (
    <div className="card">
      <div className="card-header">React Fetch 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>
  );
}

export default App;

The result will look like this:

react-fetch-put-example

React Fetch example – DELETE request

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

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

function App() {
  const baseURL = "http://localhost:8080/api";

  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 fetch(`${baseURL}/tutorials`, { method: "delete" });

      const data = await res.json();

      const result = {
        status: res.status + "-" + res.statusText,
        headers: { "Content-Type": res.headers.get("Content-Type") },
        data: data,
      };

      setDeleteResult(fortmatResponse(result));
    } catch (err) {
      setDeleteResult(err.message);
    }
  }

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

    if (id){
      try {
        const res = await fetch(`${baseURL}/tutorials/${id}`, { method: "delete" });

        const data = await res.json();

        const result = {
          status: res.status + "-" + res.statusText,
          headers: { "Content-Type": res.headers.get("Content-Type") },
          data: data,
        };

        setDeleteResult(fortmatResponse(result));
      } catch (err) {
        setDeleteResult(err.message);
      }
    }
  }
  
  const clearDeleteOutput = () => {
    setDeleteResult(null);
  }
  
  return (
    <div className="card">
      <div className="card-header">React Fetch 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>
  );
}

export default App;

The result could be like this:

react-fetch-delete-example

Conclusion

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

Instead of Fetch API, you can also use Axios which is a promise-based HTTP Client Javascript library. Kindly visit:
React Axios example – Get/Post/Put/Delete with Rest API
React example: CRUD example with React Router, Axios, Rest API

Happy Learning! See you again.

Source Code

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

Scroll to Top