CRUD
CRUD
// Api Express :
});
}, []);
</tr>
))}
</tbody>
</table>
/* Add a new item */
// Api Express :
nom,
age,
};
etudiants.push(newStudent);
res.status(201).json(newStudent);
});
// Add On react :
e.preventDefault();
fetch("http://localhost:3001/etudiants", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newStudent),
})
.then((response) => {
if (response.ok) {
navigate("/Etu");
} else {
})
.catch((error) => {
console.error("Error:", error);
});
};
/* Update an item */
// Api Express :
res.status(200).json(etudiants[itemIndex]);
});
// React Update :
const { id } = useParams(); // Get the student ID from the URL
console.log(id);
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) => {
// Optionally, you can set some error state here to display a message to the user
});
}, [id]);
e.preventDefault();
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 {
})
.catch((error) => {
console.error("Error:", error);
});
};
/* Delete an item */
// Api Express :
} else {
res.status(404).json({ message: "Student not found" }); // Student not found } });
// React Delete :
fetch(`http://localhost:3001/etudiant/${id}`, {
method: "DELETE",
})
.then((response) => {
if (response.ok) {
setEtudiants((prevEtudiants) =>
);
} else {
})
.catch((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) => (
<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}
>
Modifier
</button>
<button
style={styles.deleteButton}
>
Supprimer
</button>
</td>
</tr>
))}
</tbody>
</table>