React Google Sheet CRUD app - Get and Delete Data from Google Sheet Part 3/4

Sat Nov 20 2021

This is the third tutorial of React Google Sheet CRUD app series. In this tutorial we will retrieve and delete data from google sheet using sheet.best. In the last part we have written the functionality to add data into google sheets.

In src/pages/Home.js, paste the following

import { Link } from "react-router-dom";
import { useEffect, useState } from "react";

const Home = () => {
  const [data, setData] = useState();

  const getData = async () => {
    try {
      const res = await fetch(
        "https://sheet.best/api/sheets/bff990d0-8ada-43e9-97eb-0ad668bb19ec?_format=index"
      );
      const data = await res.json();
      setData(Object.keys(data).map((key) => data[key]));
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getData();
  }, []);

  const handleDelete = async (rowIndex) => {
    try {
      const res = await fetch(
        `https://sheet.best/api/sheets/bff990d0-8ada-43e9-97eb-0ad668bb19ec/${rowIndex}`,
        {
          method: "DELETE",
        }
      );
      if (res.ok) {
        const updatedData = data.filter((_, i) => i !== rowIndex);
        setData(updatedData);
      }
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div className="accordion" id="accordionExample">
      {data?.map((item, i) => (
        <div className="accordion-item" key={i}>
          <h2 className="accordion-header" id={`heading${i}`}>
            <button
              className="accordion-button"
              type="button"
              data-bs-toggle="collapse"
              data-bs-target={`#collapse${i}`}
              aria-expanded="true"
              aria-controls={`collapse${i}`}
            >
              {item.date}
            </button>
          </h2>
          <div
            id={`collapse${i}`}
            className="accordion-collapse collapse"
            aria-labelledby={`heading${i}`}
            data-bs-parent="#accordionExample"
          >
            <div className="accordion-body">
              <div className="d-flex justify-content-between align-items-center">
                <span>
                  <strong className="display-6">{item.name}</strong> ---{" "}
                  {item.email}
                </span>
                <span>
                  <Link to={`/edit/${i}`} style={{ textDecoration: "none" }}>
                    Edit
                  </Link>
                  <button
                    className="btn btn-sm btn-danger ms-1"
                    onClick={() => handleDelete(i)}
                  >
                    X
                  </button>
                </span>
              </div>
              <p>{item.message}</p>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

export default Home;

At the top, we imported Link from react-router-dom, useEffect and useState hooks from react. We then initialized a state to hold data and initially its null.

In getData function, we are making a GET request to sheet.best endpoint to obtain data from google sheets. Object.keys(data).map((key) => data[key]) is converting the response we got into array and then we are setting it in state. In useEffect hook, we are calling the getData function so that whenever component mounts this function will be called.

In return statement, we are rendering bootstrap accordion. We are looping through the state which is an array and rendering the fields. Additionally, we have added link to Edit page and a button to delete the data. Path to edit page is /edit/${i}, where i is the index which we are getting from the loop and we need it because if you take a look at App.js file you will see path to Edit page is /edit/:rowIndex. So we need to provided the row index in order to edit specific row in google sheet.

The delete button calls handleDelete function which takes index as argument. We have defined handleDelete function after the useEffect hook which makes a DELETE request to sheet.best endpoint but this time it also takes rowIndex in url in order to know which row in google sheet is to be deleted.

Add a few more records in google sheet from /add route and then try deleting them. Everything should work as expected. In the next part which will be final part of this series we will work on updating the record.

Previous Parts

Share

Privacy Policy
icon
icon
icon
icon

Developed By Farhan Farooq