TEXT: CODE OPTIMIZATION 03 - AVOID MULTIPLE API CALLS IN A SINGLE EVENT

Back end code

utilities.php

<?php
  header('Content-Type: application/json');
  header("Access-Control-Allow-Origin: *");

  class Utils {
    function getContacts($myConn, $userId){
      $sql = "SELECT * FROM tblcontacts
              WHERE contact_userId = :userId
              ORDER BY contact_name";
      $stmt = $myConn->prepare($sql);
      $stmt->bindParam(':userId', $userId);
      $stmt->execute();
      $returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
      unset($conn); unset($stmt);
      return $returnValue;
    }

    function getGroups($myConn){
      $sql = "SELECT * FROM tblgroups ORDER BY grp_name";
      $stmt = $myConn->prepare($sql);
      $stmt->execute();
      $returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
      unset($myConn); unset($stmt);
      return $returnValue;
    }
 

    function getContactsGroups($json){
      include "connection-pdo.php";

      $json = json_decode($json, true);
      $returnValue = array(
          "contacts" => $this->getContacts($conn, $json['userId']),
          "groups" => $this->getGroups($conn));

      return json_encode($returnValue);
    }
  }



  //submitted by the client - operation and json
  if ($_SERVER['REQUEST_METHOD'] == 'GET'){
    $operation = $_GET['operation'];
    $json = $_GET['json'];
  }else if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $operation = $_POST['operation'];
    $json = $_POST['json'];
  }

  $utils = new Utils();
  switch($operation){
    case "getContactsGroups":
      echo $utils->getContactsGroups($json);
      break;
    }

?>

 

Front End:

Next JS:

"use client";

import { useSearchParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import axios from "axios";
import {
  Button,
  Table,
  Row,
  Col,
  Modal,
  Container,
  Form,
} from "react-bootstrap";
import * as Icon from "react-bootstrap-icons";

const Main = () => {
  const searchParams = useSearchParams();
  const [contactsList, setContactsList] = useState([]);
  const [groupssList, setGroupsList] = useState([]);
  const [showViewModal, setShowViewModal] = useState(false);
  const [showUpdateModal, setShowUpdateModal] = useState(false);
  const [searchKey, setSearchKey] = useState("");

  const fullName = searchParams.get("fullname");
  const userId = sessionStorage.userId;
  const router = useRouter();
  const mainUrl = sessionStorage.mainURL;
  //======== contact details ===================
  const [contact, setContact] = useState({
    contactId:"",
    contactName:"",
    contactPhone:"",
    contactEmail:"",
    contactAddress:"",
    contactGroup:"",
    contactGroupId:"",
  });

  const getContacts = async () => {
    const url = `${mainUrl}contacts.php`;
    const jsonData = { userId: userId };

    const response = await axios.get(url, {
      params: { json: JSON.stringify(jsonData), operation: "getContacts" },
    });

    setContactsList(response.data);
  };

  // const getGroups = async () => {
  //   const url = `${mainUrl}groups.php`;

  //   const response = await axios.get(url, {
  //     params: { json: "", operation: "getGroups" },
  //   });
  //   setGroupsList(response.data);
  // };

  const addContact = () => {
    sessionStorage.setItem("userId", userId);
    router.push("/addcontact");
  };

  const getContactDetails = async (contactId) => {
    const url = `${mainUrl}contacts.php`;
    const jsonData = { contactId: contactId };
    const response = await axios.get(url, {
      params: {
        json: JSON.stringify(jsonData),
        operation: "getContactDetails",
      },
    });
    const thisContact = response.data[0];
    setContact({
      contactId:thisContact.contact_id,
      contactName:thisContact.contact_name,
      contactPhone:thisContact.contact_phone,
      contactEmail:thisContact.contact_email,
      contactAddress:thisContact.contact_address,
      contactGroup:thisContact.grp_name,
      contactGroupId:thisContact.contact_group,
    });
  };

  const showViewModalForm = (contactId) => {
    getContactDetails(contactId);
    setShowViewModal(true);
  };

  const showUpdateModalForm = (contactId) => {
    getContactDetails(contactId);
    setShowUpdateModal(true);
  };

  const updateContact = async () => {
    const url = `${mainUrl}contacts.php`;

    const jsonData = {
      contactId: contact.contactId,
      contactName: contact.contactName,
      contactEmail: contact.contactEmail,
      contactPhone: contact.contactPhone,
      contactAddress: contact.contactAddress,
      contactGroupId: contact.contactGroupId,
    };

    const formData = new FormData();
    formData.append("operation", "updateContact");
    formData.append("json", JSON.stringify(jsonData));

    const response = await axios({
      url: url,
      method: "POST",
      data: formData,
    });

    if (response.data == 1) {
      getContacts();
      alert("You have successfully UPDATED your contact!");
    } else {
      alert("UPDATE failed!");
    }
  };

  const deleteContact = async (contactId) => {
    if (confirm("Are you sure you want to delete this contact?")) {
      const url = `${mainUrl}contacts.php`;

      const jsonData = {
        contactId: contactId,
      };

      const formData = new FormData();
      formData.append("operation", "deleteContact");
      formData.append("json", JSON.stringify(jsonData));

      const response = await axios({
        url: url,
        method: "POST",
        data: formData,
      });

      if (response.data == 1) {
        getContacts();
        alert("You have successfully DELETED your contact!");
      } else {
        alert("DELETE failed!");
      }
    }
  };

  const searchContact = async() => {
    const url = `${mainUrl}contacts.php`;
    const jsonData = { userId: userId, searchKey:searchKey };

    const response = await axios.get(url, {
      params: { json: JSON.stringify(jsonData), operation: "searchContact" },
    });

    setContactsList(response.data);
  };

  const getRecords = async() =>{
    const url = `${mainUrl}utilities.php`;

    const jsonData = {userId: userId,};

    const response = await axios.get(url, {
      params: { json: JSON.stringify(jsonData), operation: "getContactsGroups" },
    });

    setContactsList(response.data.contacts);
    setGroupsList(response.data.groups);
  }

  useEffect(() => {
    getRecords();
    // getContacts();
    // getGroups();
  }, []);

  return (
    <>
      <Container>
        <h1>Contacts of {fullName}</h1>
        <Row className="d-flex align-items-center">
          <Col md={10}>
            <Form.Control
              type="search"
              placeholder="Search Contacts"
              size="sm"
              className="m-3"
              value={searchKey}
              onChange={(e) => {
                setSearchKey(e.target.value);
              }}
            />
          </Col>
          <Col md={2} className="text-center">
            <Button onClick={searchContact} size="sm" className="w-100">
              <Icon.Search size={15} /> Search
            </Button>
          </Col>
        </Row>
        <Table striped hover>
          <thead bgcolor="red">
            <tr>
              <th className="bg-dark text-white">Name</th>
              <th className="bg-dark text-white">Address</th>
              <th className="bg-dark text-white">Phone</th>
              <th className="bg-dark text-white">Actions</th>
            </tr>
          </thead>
          <tbody>
            {contactsList.map((contact, index) => {
              return (
                <tr key={index}>
                  <td>{contact.contact_name}</td>
                  <td>{contact.contact_address}</td>
                  <td>{contact.contact_phone}</td>
                  <td>
                    <Icon.Eye
                      className="ms-3"
                      color="green"
                      style={{ cursor: "pointer" }}
                      onClick={() => {
                        showViewModalForm(contact.contact_id);
                      }}
                    />
                    <Icon.Pen
                      className="ms-3"
                      color="blue"
                      style={{ cursor: "pointer" }}
                      onClick={() => {
                        showUpdateModalForm(contact.contact_id);
                      }}
                    />
                    <Icon.Trash
                      className="ms-3"
                      color="red"
                      style={{ cursor: "pointer" }}
                      onClick={() => {
                        deleteContact(contact.contact_id);
                      }}
                    />
                  </td>
                </tr>
              );
            })}
          </tbody>
        </Table>
        <div className="fixed-bottom right-0 text-end p-2">
          <Button onClick={addContact}>
            <Icon.PlusCircle size={25} />
          </Button>
        </div>
        {/* ===================== VIEW MODAL ============== */}
        <Modal
          show={showViewModal}
          onHide={() => {
            setShowViewModal(false);
          }}
        >
          <Modal.Header closeButton className="bg-success text-white">
            <Modal.Title>View Record Details</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Table>
              <tbody>
                <tr>
                  <td>Name</td>
                  <td>{contact.contactName}</td>
                </tr>
                <tr>
                  <td>Address</td>
                  <td>{contact.contactAddress}</td>
                </tr>
                <tr>
                  <td>Phone</td>
                  <td>{contact.contactPhone}</td>
                </tr>
                <tr>
                  <td>Email</td>
                  <td>{contact.contactEmail}</td>
                </tr>
                <tr>
                  <td>Group</td>
                  <td>{contact.contactGroup}</td>
                </tr>
              </tbody>
            </Table>
          </Modal.Body>
          <Modal.Footer>
            <Button
              variant="secondary"
              onClick={() => {
                setShowViewModal(false);
              }}
            >
              Close
            </Button>
          </Modal.Footer>
        </Modal>

        {/* ===================== UPDATE MODAL ============== */}
        <Modal
          show={showUpdateModal}
          onHide={() => {
            setShowUpdateModal(false);
          }}
        >
          <Modal.Header closeButton className="bg-success text-white">
            <Modal.Title>UPDATE CONTACT</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Table>
              <tbody>
                <tr>
                  <td>Name</td>
                  <td>
                    <Form.Control
                      type="text"
                      value={contact.contactName}
                      onChange={(e) => {
                        setContact({...contact, contactName: e.target.value});
                      }}
                    />
                  </td>
                </tr>
                <tr>
                  <td>Address</td>
                  <td>
                    <Form.Control
                      type="text"
                      value={contact.contactAddress}
                      onChange={(e) => {
                        setContact({...contact, contactAddress: e.target.value});
                      }}
                    />
                  </td>
                </tr>
                <tr>
                  <td>Phone</td>
                  <td>
                    <Form.Control
                      type="text"
                      value={contact.contactPhone}
                      onChange={(e) => {
                        setContact({...contact, contactPhone: e.target.value});
                      }}
                    />
                  </td>
                </tr>
                <tr>
                  <td>Email</td>
                  <td>
                    <Form.Control
                      type="text"
                      value={contact.contactEmail}
                      onChange={(e) => {
                        setContact({...contact, contactEmail: e.target.value});
                      }}
                    />
                  </td>
                </tr>
                <tr>
                  <td>Group</td>
                  <td>
                    <Form.Select
                      value={contact.contactGroupId}
                      onChange={(e) => {
                        setContact({...contact, contactGroupId: e.target.value});
                      }}
                    >
                      {groupssList.map((group, index) => {
                        return (
                          <option value={group.grp_id} key={group.grp_id}>
                            {group.grp_name}
                          </option>
                        );
                      })}
                    </Form.Select>
                  </td>
                </tr>
              </tbody>
            </Table>
          </Modal.Body>
          <Modal.Footer>
            <Button
              variant="secondary"
              onClick={() => {
                setShowUpdateModal(false);
              }}
            >
              Close
            </Button>
            <Button
              variant="primary"
              onClick={() => {
                updateContact();
                setShowUpdateModal(false);
              }}
            >
              Update
            </Button>
          </Modal.Footer>
        </Modal>
      </Container>
    </>
  );
};

export default Main;


 

 

No comments:

Post a Comment

IMAGE : OPTIMIZING API END POINTS USING CLASSES IN PHP

 BACK END users.php   TEXT VERSION connection.php   TEXT VERSION FRONT END main.dart (LOGIN PAGE) register.dart   TEXT VERSION