React Google Sheets CRUD app - Add Data into Google Sheet Part 2/4

Tue Nov 16 2021

This is the second tutorial of React Google Sheets CRUD app series. In this tutorial we will insert data from our react app into google sheet using sheet.best. In the previous tutorial, we have already setup google sheet, sheet.best and boilerplate for react app. You can find the Part 1 here.

Go to src/pages/Add.js and paste the following

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

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

  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",
        {
          method: "POST",
          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">Add</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">Add</button>
      </div>
    </form>
  );
};

export default Add;

At the top, we imported useState hook from react and useHistory hook from react-router-dom. We then called useHistory hook and stored it in history variable. After that we defined our initial state. We are building a feedback form so fields here are name, email, message and date.

In return statement, we are rendering a form with name, email, message fields and a button to submit the form. We have also attached value attribute to each field and onChange function which points to handleChange function. We have also attached handleSubmit function to form tag itself.

handleChange function captures the values provided by user in form and set the state values accordingly. In handleSubmit function, first we prevented the default behavior of form submission and after that we are making a POST request to the sheet.best endpoint which we configured in the previous tutorial. If res.ok return true then user will be navigated to home page.

One thing to remember here is that anyone with your sheet.best endpoint can make CRUD requests to your google sheet as in the setup tutorial we changed the permission Anyone with the link from Viewer to Editor. For this tutorial, I am not going to secure this endpoint but for real world scenarios you should secure this endpoint and the best way is to perform CRUD operations on server side and from frontend call the backend APIs.

Open terminal and run npm start. From Navbar click on Add. Fill the form and submit. Upon successful submission, you will be redirected to home page. Check your google sheet now you will see an entry containing the details you submitted from your react app. Date field is auto-generated because we set the date in our state as date: new Date().toString()

In the next part, we will work on getting the data from google sheet and render it on home page of our react app.

Previous Parts

Share

Privacy Policy
icon
icon
icon
icon

Developed By Farhan Farooq