0% found this document useful (0 votes)
7 views9 pages

CRUD

The document provides a simplified React CRUD application code for managing a list of students (etudiants) using Express as the backend. It includes functionalities to create, read, update, and delete student records, with corresponding API routes and React components for handling user interactions. The code demonstrates how to fetch data from the server, handle form submissions, and update the UI accordingly.

Uploaded by

sahrizaid8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

CRUD

The document provides a simplified React CRUD application code for managing a list of students (etudiants) using Express as the backend. It includes functionalities to create, read, update, and delete student records, with corresponding API routes and React components for handling user interactions. The code demonstrates how to fetch data from the server, handle form submissions, and update the UI accordingly.

Uploaded by

sahrizaid8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Simplified React CRUD Application Code

import React, { useState, useEffect } from "react";

const [etudiants, setEtudiants] = useState([]);

/* Get all items */

// Api Express :

app.get("/etudiants", (req: Request, res: Response) => {

res.json(etudiants); // Correct order and typing for request and response

});

// Fetch items from the server


useEffect(() => {

fetch("http://localhost:3001/etudiants") // Replace with your backend URL

.then((response) => response.json())

.then((data) => setEtudiants(data))

.catch((error) => console.error("Error fetching students:", error));

}, []);

</tr>

))}

</tbody>

</table>
/* Add a new item */

// Api Express :

app.post("/etudiants", (req: Request, res: Response) => {

const { nom, age } = req.body;

const newStudent: Etudiant = {

id: etudiants.length > 0 ? etudiants[etudiants.length - 1].id + 1 : 1,

nom,

age,

};

etudiants.push(newStudent);

res.status(201).json(newStudent);

});

// Add On react :

const [nom, setNom] = useState("");

const [age, setAge] = useState("");

const navigate = useNavigate();

const handleSubmit = (e) => {

e.preventDefault();

const newStudent = { nom: nom.trim(), age: parseInt(age, 10) };

fetch("http://localhost:3001/etudiants", {

method: "POST",

headers: {

"Content-Type": "application/json",
},

body: JSON.stringify(newStudent),

})

.then((response) => {

if (response.ok) {

// If response is ok, navigate to the new page

navigate("/Etu");

} else {

// Handle failure if the response isn't OK

console.error("Failed to add student:", response.statusText);

})

.catch((error) => {

// Catch any errors that occurred during the fetch operation

console.error("Error:", error);

});

};
/* Update an item */

// Api Express :

app.put("/etudiants/:id", (req: Request, res: Response) => {

const id = req.params.id; // Correctly access the id from the params

const { nom, age } = req.body;

// Find the index of the student to be updated

const itemIndex = etudiants.findIndex((e) => e.id === Number(id));

// Update the student data

etudiants[itemIndex] = { id: Number(id), nom, age };

// Respond with the updated student

res.status(200).json(etudiants[itemIndex]);

});

// React Update :
const { id } = useParams(); // Get the student ID from the URL

const [nom, setNom] = useState("");

const [age, setAge] = useState("");

const navigate = useNavigate();

console.log(id);

// Fetch the student's data

useEffect(() => {

fetch(`http://localhost:3001/etudiant/${id}`)

.then((response) => {

if (!response.ok) {
throw new Error("Student not found or other error");

return response.json();

})

.then((data) => {

setNom(data.nom);

setAge(data.age.toString());

})

.catch((error) => {

console.error("Error fetching student:", error);

// Optionally, you can set some error state here to display a message to the user

});

}, [id]);

const handleSubmit = (e) => {

e.preventDefault();

const updatedStudent = { nom: nom.trim(), age: parseInt(age, 10) };

fetch(`http://localhost:3001/etudiants/${id}`, {

method: "PUT",

headers: {

"Content-Type": "application/json" },

body: JSON.stringify(updatedStudent),})

.then((response) => {

if (response.ok) {
// If the response is successful, navigate to the desired page

navigate("/Etu");

} else {

// If the response is not OK, log an error message

console.error("Failed to update student:", response.statusText);}

})

.catch((error) => {

// Catch any errors that happen during the fetch operation

console.error("Error:", error);

});

};

/* Delete an item */
// Api Express :

app.delete("/etudiant/:id", (req: Request, res: Response) => {

const id = req.params.id; // Correctly access the id from the params

// Find the index of the student to be deleted

const itemIndex = etudiants.findIndex((e) => e.id === Number(id));

if (itemIndex !== -1) {

// Remove the student from the array

const deletedItem = etudiants.splice(itemIndex, 1);

res.status(200).json(deletedItem); // Respond with the deleted student

} else {

res.status(404).json({ message: "Student not found" }); // Student not found } });
// React Delete :

const handleDelete = (id) => {

fetch(`http://localhost:3001/etudiant/${id}`, {

method: "DELETE",

})

.then((response) => {

if (response.ok) {

// Update the local state after deleting the student

setEtudiants((prevEtudiants) =>

prevEtudiants.filter((etudiant) => etudiant.id !== id)

);

} else {

console.error("Failed to delete student:", response.statusText);

})

.catch((error) => {

console.error("Error:", error) });

};
// How to fetch all etudiants on code jsx :

<table style={styles.table}>

<thead>

<tr style={styles.headerRow}>

<th style={styles.headerCell}>ID</th>

<th style={styles.headerCell}>Name</th>

<th style={styles.headerCell}>Age</th>

<th style={styles.headerCell}>Actions</th>

</tr>

</thead>

<tbody>

{etudiants.map((etudiant) => (

<tr key={etudiant.id} style={styles.bodyRow}>

<td style={styles.bodyCell}>{etudiant.id}</td>

<td style={styles.bodyCell}>{etudiant.nom}</td>

<td style={styles.bodyCell}>{etudiant.age}</td>

<td style={styles.bodyCell}>

<button

style={styles.editButton}

onClick={() => navigate(`/UpdateEtu/${etudiant.id}`)}

>

Modifier

</button>
<button

style={styles.deleteButton}

onClick={() => handleDelete(etudiant.id)}

>

Supprimer

</button>

</td>

</tr>

))}

</tbody>

</table>

You might also like