MitraIde

News

Cari Di Situs Ini

Kamis, 30 Mei 2024

Crud sederhana di ReactJs

 

Kali ini kita akan belajar menggunakan CRUD sederhana di reactJs

untuk file file seperti berikut :


App.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import Login from './Login';
import Home from './Home';
import About from './About';
import Contact from './Contact';
import Halaman from './Halaman';
import Siswa from './Siswa';
import SiswaEdit from './SiswaEdit';


function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Siswa />} />
<Route path="/SiswaEdit/:id" element={<SiswaEdit />} />
<Route path="/login" element={<Login />} />
<Route path="/home" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
);
}

export default App;


Siswa.js:

import React, { useState, useEffect } from 'react';
const Siswa = () => {
const [siswaList, setSiswaList] = useState([]);
const fetchSiswaList = async () => {
try {
const response = await fetch("http://localhost/belajar/siswa/siswa.php?action=getAll");
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const data = await response.json();
setSiswaList(data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
const handleAddSiswa = async () => {
console.log("insert start");
const formData = new FormData();
formData.append('nama', 'nama siswa');
formData.append('foto', 'foto siswa');
try {
const response = await fetch('http://localhost/belajar/siswa/siswa.php?action=insert', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('Failed to add data');
}else{
fetchSiswaList();
}
} catch (error) {
console.error('Error adding data:', error);
}
};
const handleDelete = async (id) => {
try {
const formData = new FormData();
formData.append('id', id);
const response = await fetch("http://localhost/belajar/siswa/siswa.php?action=delete", {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('Failed to delete data');
}else{
fetchSiswaList();
}
} catch (error) {
console.error('Error deleting data:', error);
}
}
const handleEdit = async (id, nama, foto) => {
try {
const formData = new FormData();
formData.append('id', id);
formData.append('nama', "nama baru");
formData.append('foto', "foto bary");
const response = await fetch("http://localhost/belajar/siswa/siswa.php?action=edit", {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('Failed to edit data');
}else{
fetchSiswaList();
}
} catch (error) {
console.error('Error editing data:', error);
}
};
const handleRefresh = () => {
console.log("Refresh Data");
fetchSiswaList();
};
useEffect(() => {
fetchSiswaList();
}, []);
return (
<div>
<h1>Daftar Siswa</h1>
<button onClick={handleAddSiswa}>Tambah Data</button>
<button onClick={handleRefresh}>Refresh Data</button>
<table>
<thead>
<tr>
<th>ID</th>
<th>Nama</th>
<th>Foto</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
{siswaList.map((siswa) => (
<tr>
<td>{siswa.id}</td>
<td>{siswa.nama}</td>
<td>{siswa.foto}</td>
<td><button onClick={() => handleEdit(siswa.id, "Nama Baru", "Foto Baru")}>Edit</button></td>
<td><button onClick={() => handleDelete(siswa.id)}>Delete</button></td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default Siswa;


SiswaEdit.js:

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
const SiswaEdit = () => {
const { id } = useParams();
const [siswa, setSiswa] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchSiswaEdit = async () => {
try {
const response = await fetch("http://localhost/belajar/siswa/siswa.php?action=getDetail&id="+id);
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const data = await response.json();
if (Array.isArray(data) && data.length > 0) {
setSiswa(data[0]);
} else {
setError('Data not found');
}
setLoading(false);
} catch (error) {
setError(error.message);
setLoading(false);
}
};
fetchSiswaEdit();
}, [id]);
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
const handleUpdate = async () => {
const formData = new FormData();
formData.append('id', siswa.id);
formData.append('nama', siswa.nama);
formData.append('foto', siswa.foto);
try {
const response = await fetch('http://localhost/belajar/siswa/siswa.php?action=edit', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('Failed to update data');
}
alert('Data updated successfully');
} catch (error) {
console.error('Error updating data:', error);
}
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setSiswa((prevSiswa) => ({
...prevSiswa,
[name]: value
}));
};
return (
<div>
<h2 style={{ color: 'green' }}>SiswaEdit Page</h2>
{siswa ? (
<form>
<div>
<label>ID Siswa:</label>
<input
type="text"
name="id"
value={siswa.id}
readOnly
/>
</div>
<div>
<label>Nama:</label>
<input
type="text"
name="nama"
value={siswa.nama}
onChange={handleInputChange}
/>
</div>
<div>
<label>Foto:</label>
<input
type="text"
name="foto"
value={siswa.foto}
onChange={handleInputChange}
/>
</div>
<button type="button" onClick={handleUpdate}>Update</button>
</form>
) : (
<p>Data tidak ditemukan</p>
)}
</div>
);
};
export default SiswaEdit;


Untuk Apinya akan saya posting di kemudian hari ya..