LOGIN
"use client";
import { useState, useEffect } from "react";
import axios from 'axios';
import { useRouter } from 'next/navigation';
import Link from "next/link";
const Login = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const router = useRouter();
const login = async() => {
const url = `${sessionStorage.mainURL}users.php`; //back tick key b4 1
//const url = sessionStorage.mainURL + "users.php";
//const url = "http://localhost/contacts-api/users.php"
const jsonData = {username:username, password:password}
var response = await axios.get(url, {
params:{json: JSON.stringify(jsonData), operation: "login"}
});
//check if valid user
if(response.data.length > 0){
let params = new URLSearchParams();
params.append('fullname', response.data[0].usr_fullname);
//params.append('userId', response.data[0].usr_id);
sessionStorage.setItem("userId", response.data[0].usr_id);
router.push(`/main?${params}`);
}else{
alert("Invlid username or password.");
}
}
useEffect(()=>{
sessionStorage.setItem("mainURL", "http://localhost/contacts-api/");
}, []);
return (
<>
<h1>Add Records to MySQL Database</h1>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => {
setUsername(e.target.value);
}}
/>
<br/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
<br/>
<button onClick={login}>Login</button><br/>
No Account yet? <Link href={'/register'}>Register Here!</Link>
</>
);
};
export default Login;
MAIN
"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);
};
useEffect(() => {
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