Trying to show an error on duplicate entry in database using mysql, express js, react js

Viewed 44

I have this CRUD application which is working perfectly fine. Now I am trying to add validation in it. Basically I want to show an error which will let user know that the entry you are trying to insert already exists in database.

This is what I am trying,

console.log('Value Exists!') for the server side verification.

Here is the request in the index.js file:

app.post("/api/post", (req, res) => {
  // values we will pass from the front end and recieve in the req.body.
  const { FirstName, LastName, FatherName, userCNIC, Contact, Gender } =
    req.body;
  const sqlGet = "SELECT FirstName FROM emp_table WHERE FirstName = ?";
  db.query(sqlGet, FirstName, (error, result) => {
    if (result) {
      console.log("Value Exists")
      res.send("Value Exists");
    } else {
      const sqlInsert =
        "INSERT INTO emp_table (FirstName, LastName, FatherName, userCNIC, Contact, Gender) VALUES (?, ?, ?, ?, ?, ?)";
      db.query(
        sqlInsert,
        [FirstName, LastName, FatherName, userCNIC, Contact, Gender],
        (error, result) => {
          if (error) {
            console.log(error);
          } else {
            res.send("Values inserted!");
          }
        }
      );
    }
  });
});

I don't know why, but whenever I insert the data it always shows the value exists, even if the input FirstName field is changed

And here is the client side react js file:

import React, { useEffect } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import "./AddEdit.css";
import axios from "axios";
import { toast } from "react-toastify";
import Container from "react-bootstrap/Container";
import Form from "react-bootstrap/Form";

import { useState } from "react";

const initialState = {
  FirstName: "",
  LastName: "",
  FatherName: "",
  userCNIC: "",
  Contact: "",
  Gender: "",
};

const AddEdit = () => {
  const [state, setState] = useState(initialState);

  const { FirstName, LastName, FatherName, userCNIC, Contact, Gender } = state;
  const [gender, setGender] = useState();
  const navigate = useNavigate();

  const { id } = useParams();

  // this useEffect will run when we have the id
  // when we have the id, this basically means we are updating the content.
  useEffect(() => {
    axios
      .get(`http://localhost:5000/api/get/${id}`)
      // here we will get the response in the form of array, that will contain only one data.
      // as it is fetching only single row based on the id.
      .then((resp) => setState({ ...resp.data[0] }));
  }, [id]);

  const handleSubmit = (e) => {
    var phoneno = /^\d{11,12}$/;
    var cnicno = /^\d{12,13}$/;

    // var console = window.console;
    // var console = global.console;
    // console.log = function (msg) {
    //   if (msg.includes("Email already exists!")) myFunc();
    // };

    // function myFunc() {
    //   alert("function invoked");
    // }
    // to prevent the default behavior of the browser.
    // e.preventDefault();
    // if (
    // if all fields are not filled.
    //   !FirstName ||
    //   !LastName ||
    //   !FatherName ||
    //   !userCNIC ||
    //   !Contact ||
    //   !Gender
    // ) {
    //   toast.error("Please fill in all the input fields!");

    if (!Contact.match(phoneno)) {
      // checking phone validation
      toast.error("Please provide correct phone number!");
      e.preventDefault();
    } else if (!userCNIC.match(cnicno)) {
      // checking phone validation
      toast.error("Please provide correct CNIC Number!");
      e.preventDefault();
    } else {
      // if user has no id, it means it is only adding the record.
      if (!id) {
        axios
          .post("http://localhost:5000/api/post", {
            FirstName,
            LastName,
            FatherName,
            userCNIC,
            Contact,
            Gender,
          })
          // once user is successfully able to pass the data to database, then clear the each input field.
          .then((response) => {
            if (response.data == "Value Exists") {
              return (
                <div>
                  <h1>Duplicate Entry</h1>
                </div>
              );
            }
            // setState({
            //   FirstName: "",
            //   LastName: "",
            //   FatherName: "",
            //   userCNIC: "",
            //   Contact: "",
            //   Gender: "",
            // });
          })
          .catch((err) => toast.error(err.response.data));
        toast.success("Contact added Successfully");
      } else {
        // else it is updating the record.
        axios
          .put(`http://localhost:5000/api/update/${id}`, {
            FirstName,
            LastName,
            FatherName,
            userCNIC,
            Contact,
            Gender,
          })
          .then(() => {
            setState({
              FirstName: "",
              LastName: "",
              FatherName: "",
              userCNIC: "",
              Contact: "",
              Gender: "",
            });
          })
          .catch((err) => toast.error(err.response.data));
        toast.success("Contact Updated Successfully");
      }
      // when all the data is submitted, navigate to the home page.
      setTimeout(() => navigate("/"), 500);
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setState({ ...state, [name]: value });
  };
  return (
    <div id="top-div">
      <h1>Enter Details</h1>

      <Container className="containerr">
        <Form
          onSubmit={handleSubmit}
          className="form"
          tyle={{
            margin: "auto",
            padding: "15px",
            maxWidth: "1000px",
            alignContent: "center",
            boxShadow: "0 4px 8px 0 rgba(34, 116, 194, 0.938)",
          }}
        >
          <div style={{ display: "inline-block" }}>
            <Form.Group>
              <Form.Control
                type="text"
                placeholder="Enter name"
                name="FirstName"
                onChange={handleInputChange}
                value={FirstName || ""}
                id="FirstName"
              />
            </Form.Group>
            <Form.Group>
              <Form.Control
                type="text"
                id="LastName"
                name="LastName"
                placeholder="Last Name"
                value={LastName || ""}
                onChange={handleInputChange}
              />
            </Form.Group>
          </div>

          <Form.Group>
            <Form.Control
              type="text"
              id="FatherName"
              name="FatherName"
              placeholder="Fathers name:"
              value={FatherName || ""}
              onChange={handleInputChange}
            />
          </Form.Group>
          <Form.Group>
            <Form.Control
              type="text"
              id="userCNIC"
              name="userCNIC"
              placeholder="CNIC:"
              value={userCNIC || ""}
              onChange={handleInputChange}
            />
          </Form.Group>
          <Form.Group>
            <Form.Control
              type="text"
              id="Contact"
              name="Contact"
              placeholder="Contact number"
              value={Contact || ""}
              onChange={handleInputChange}
            />
          </Form.Group>
          <Form.Group>
            <Form.Control
              type="text"
              id="Gender"
              name="Gender"
              placeholder="Gender:"
              value={Gender || ""}
              onChange={handleInputChange}
            />
          </Form.Group>
          <input type="submit" value={id ? "Update" : "Save"} />
          <Link to="/">
            <input type="button" value="Go Back" />
          </Link>
        </Form>
      </Container>
    </div>
  );
};

export default AddEdit;

1 Answers

I think result will be empty array. So you should check length of array.

db.query(sqlGet, FirstName, (error, result) => {
    // I recommend you handle error, first
    if (error) {
        return res.status(500).json({ message: "error" });
    }

    // check result(array) length
    if (result.length) {
        console.log("Value Exists");
        res.status(200).send("Value Exists");
    } else {
        // ...
    }
});
Related