React Google Sheet CRUD app - Update data Part 4/4

Sun Jul 17 2022

This is the final tutorial of React Google Sheet CRUD app series. In previous tutorials we have worked on adding the data into google sheet, retrieving and deleting data from google sheet. In this tutorial we will update data

In src/pages/Edit.js paste the following

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

const Edit = () => {
  const history = useHistory();
  const { rowIndex } = useParams();
  const [data, setData] = useState({
    name: "",
    email: "",
    message: "",
    date: new Date().toString(),
  });

  const getData = async () => {
    try {
      const res = await fetch(
        `https://sheet.best/api/sheets/bff990d0-8ada-43e9-97eb-0ad668bb19ec/${rowIndex}`
      );
      const data = await res.json();
      setData(data[0]);
    } catch (error) {
      console.log(error);
    }
  };

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

  const handleChange = (e) =>
    setData({ ...data, [e.target.name]: e.target.value });

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const res = await fetch(
        `https://sheet.best/api/sheets/bff990d0-8ada-43e9-97eb-0ad668bb19ec/${rowIndex}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        }
      );
      if (res.ok) {
        history.replace("/");
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <form style={{ maxWidth: 500, margin: "auto" }} onSubmit={handleSubmit}>
      <h1 className="text-muted text-center">Edit</h1>
      <div className="mb-3">
        <label htmlFor="name" className="form-label">
          Name
        </label>
        <input
          type="text"
          className="form-control"
          name="name"
          value={data.name}
          onChange={handleChange}
        />
      </div>
      <div className="mb-3">
        <label htmlFor="email" className="form-label">
          Email
        </label>
        <input
          type="email"
          className="form-control"
          name="email"
          value={data.email}
          onChange={handleChange}
        />
      </div>
      <div className="mb-3">
        <label htmlFor="message" className="form-label">
          Message
        </label>
        <textarea
          name="message"
          cols="30"
          rows="3"
          className="form-control"
          value={data.message}
          onChange={handleChange}
        />
      </div>
      <div className="text-center">
        <button className="btn btn-primary">Update</button>
      </div>
    </form>
  );
};

export default Edit;

At the top, we imported useParams and useHistory hooks from react-router-dom. We also imported useEffect and useState hooks from react. We destructured rowIndex from params as the path to this route contains rowIndex that's why we have access to rowIndex. This file is almost similar to Add.js. We are displaying a form here just like we displayed it in Add.js file however the form fields will be pre-populated with the data of the specific row so for that when component mounts we are making a GET request to sheet.best endpoint providing rowIndex in url and setting the response in state.

handleChange function is the same as it is in Add.js file. handleSubmit functions makes a PUT request to the sheet.best endpoint providing rowIndex in url in order to update the specific row. Upon successful update, we are navigating the user back to home page.

Give it a try now. Run the server from home page click Edit on any record, from Edit route, make changes in form and submit.

The tutorial is now complete. We are now able to perform CRUD operations from our react app to google sheets.

Github repo

Share

Privacy Policy
icon
icon
icon
icon

Developed By Farhan Farooq