'Intergrating .post, .put and .delete into Registration Form
Hoping this will help with my problem.
I have a class project where I'm trying to create a registration form where the information is sent and received from a database. I've managed to get the server to work and I'm able to read the data in my client, but nothing more.
How do I go about integrating the other commands into my code and how do I swap out my Id's with the Id's that mongodb create?
I really appreciate the time anyone take to looking at my problem.
Here the code:
import React, { useState, useEffect, Fragment } from "react";
import staffs from "./api";
import ReadOnlyRow from "./ReadOnlyRow";
import EditableRow from "./EditableRow";
import "./staffMember.css";
const StaffMember = () => {
const [contacts, setContacts] = useState([]);
useEffect(() => {
async function fetchData() {
const { data } = await staffs.get("/staffs");
setContacts(data);
}
fetchData();
}, []);
const [openForm, setOpenForm] = useState(false);
const idRandom = () => {
return Date.now();
};
const [id, setId] = useState(idRandom());
const [addFormData, setAddFormData] = useState({
name: "",
surname: "",
email: "",
bank: "",
});
const [editFormData, setEditFormData] = useState({
name: "",
surname: "",
email: "",
bank: "",
});
const [editContactId, setEditContactId] = useState(null);
const handleAddFormChange = (event) => {
event.preventDefault();
const fieldName = event.target.getAttribute("name");
const fieldValue = event.target.value;
const newFormData = { ...addFormData };
newFormData[fieldName] = fieldValue;
setAddFormData(newFormData);
};
const handleEditFormChange = (event) => {
event.preventDefault();
const fieldName = event.target.getAttribute("name");
const fieldValue = event.target.value;
const newFormData = { ...editFormData };
newFormData[fieldName] = fieldValue;
setEditFormData(newFormData);
};
const handleAddFormSubmit = (event) => {
event.preventDefault();
const newContact = {
id,
name: addFormData.name,
surname: addFormData.surname,
email: addFormData.email,
bank: addFormData.bank,
};
const newContacts = [...contacts, newContact];
setContacts(newContacts);
Array.from(document.querySelectorAll("input")).forEach(
(input) => (input.value = "")
);
setOpenForm(false);
setId(idRandom());
};
const handleEditFormSubmit = (event) => {
event.preventDefault();
const editedContact = {
id: editContactId,
name: editFormData.name,
surname: editFormData.surname,
email: editFormData.email,
bank: editFormData.bank,
};
const newContacts = [...contacts];
const index = contacts.findIndex((contact) => contact.id === editContactId);
newContacts[index] = editedContact;
setContacts(newContacts);
setEditContactId(null);
};
const handleEditClick = (event, contact) => {
event.preventDefault();
setEditContactId(contact.id);
const formValues = {
name: contact.name,
surname: contact.surname,
email: contact.email,
bank: contact.bank,
};
setEditFormData(formValues);
};
const handleCloseClick = () => {
setOpenForm(false);
};
const handleCancelClick = () => {
setEditContactId(null);
};
const handleDeleteClick = (contactId) => {
const newContacts = [...contacts];
const index = contacts.findIndex((contact) => contact.id === contactId);
staffs.delete(`/${contactId}`);
newContacts.splice(index, 1);
setContacts(newContacts);
};
return (
<div>
<h1 style={{ color: "pink" }}>Staff</h1>
<button onClick={() => setOpenForm(!openForm)}>
{"Add a new staff member"}
</button>
{openForm && (
<div className="createForm">
<h2 style={{ color: "pink" }}>Add a Contact</h2>
<form onSubmit={handleAddFormSubmit}>
<input
type="text"
name="name"
required="required"
placeholder="Enter a name..."
onChange={handleAddFormChange}
/>
<input
type="text"
name="surname"
required="required"
placeholder="Enter a surname..."
onChange={handleAddFormChange}
/>
<input
type="email"
name="email"
required="required"
placeholder="Enter an email address..."
onChange={handleAddFormChange}
/>
<input
type="text"
name="bank"
required="required"
placeholder="Enter a bank account..."
onChange={handleAddFormChange}
/>
<button type="submit">Add</button>
<button type="button" onClick={handleCloseClick}>
Cancel
</button>
</form>
</div>
)}
<form onSubmit={handleEditFormSubmit}>
<div>
{contacts.map((contact) => (
<Fragment key={contact.id}>
{editContactId === contact.id ? (
<EditableRow
contact={contact}
editFormData={editFormData}
handleEditFormChange={handleEditFormChange}
handleCancelClick={handleCancelClick}
/>
) : (
<ReadOnlyRow
contact={contact}
handleEditClick={handleEditClick}
handleDeleteClick={handleDeleteClick}
/>
)}
</Fragment>
))}
</div>
</form>
</div>
);
};
export default StaffMember;
staffs in ./api folder:
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8080",
});
My routes:
const router = require("express").Router();
const Staff = require("../models/Staff");
router.get("/", (req, res) => {
Staff.find((err, result) => {
if (err) throw new Error(err);
res.json(result);
});
});
router.post("/", (req, res) => {
Staff.create(req.body, (err, result) => {
if (err) throw new Error(err);
res.json(result);
});
});
router.put("/:id", (req, res) => {
Staff.findOneAndUpdate(
{ _id: req.params.id },
req.body,
{ new: true },
(err, result) => {
if (err) throw new Error(err);
res.json(result);
}
);
});
router.delete("/:id", (req, res) => {
Staff.findOneAndRemove({ _id: req.params.id }, (err, result) => {
if (err) throw new Error(err);
res.end();
});
});
module.exports = router;
And my mongoose schema:
const mongoose = require("mongoose");
const StaffSchema = new mongoose.Schema({
id: String,
name: String,
surname: String,
email: String,
bank: String,
});
module.exports = mongoose.model("Staff", StaffSchema);
ReadOnly:
import React from "react";
const ReadOnlyRow = ({ contact, handleEditClick, handleDeleteClick }) => {
return (
<div className="card">
<div>
<p>ID: {contact.id}</p>
<p>
Name: {contact.name} {contact.surname}
</p>
<p>E-mail: {contact.email}</p>
</div>
<div>
<button
type="button"
onClick={(event) => handleEditClick(event, contact)}
>
Edit
</button>
<button type="button" onClick={() => handleDeleteClick(contact.id)}>
Delete
</button>
</div>
</div>
);
};
export default ReadOnlyRow;
Editable:
import React from "react";
const EditableRow = ({
contact,
editFormData,
handleEditFormChange,
handleCancelClick,
}) => {
return (
<div className="card">
<p>ID: {contact.id}</p>
<p>
Name:
<input
type="text"
required="required"
placeholder="Enter a first name..."
name="name"
value={editFormData.name}
onChange={handleEditFormChange}
></input>
<input
type="text"
required="required"
placeholder="Enter a surname..."
name="surname"
value={editFormData.surname}
onChange={handleEditFormChange}
></input>
</p>
<p>
E-mail:{" "}
<input
type="email"
required="required"
placeholder="Enter an email address..."
name="email"
value={editFormData.email}
onChange={handleEditFormChange}
></input>
</p>
<div>
<button type="submit">Save</button>
<button type="button" onClick={handleCancelClick}>
Cancel
</button>
</div>
</div>
);
};
export default EditableRow;
Let me know if I have missed anything :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
