import { useState } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useForm } from 'react-hook-form'; import api from '../api/axios'; // Import Axios instance ที่มี JWT Interceptor import { FaPlus, FaTrash } from 'react-icons/fa'; // ฟังก์ชันสำหรับเรียก API (Read) const fetchDoctors = async () => { const { data } = await api.get('/doctors'); return data; }; // ฟังก์ชันสำหรับเพิ่มแพทย์ใหม่ (Create) const addDoctor = async (newDoctor) => { const { data } = await api.post('/doctors', newDoctor); return data; }; // ฟังก์ชันสำหรับลบแพทย์ (Delete) const deleteDoctor = async (id) => { await api.delete(`/doctors/${id}`); }; export default function DoctorsPage() { const queryClient = useQueryClient(); const [isModalOpen, setIsModalOpen] = useState(false); // 1. ดึงข้อมูลแพทย์จาก API (Read) const { data: doctors, isLoading, isError, error } = useQuery({ queryKey: ['doctors'], queryFn: fetchDoctors, }); // 2. จัดการฟอร์มสำหรับเพิ่มแพทย์ (Create) const { register, handleSubmit, reset, formState: { errors } } = useForm(); // 3. จัดการการเพิ่มข้อมูล (Mutation) const addDoctorMutation = useMutation({ mutationFn: addDoctor, onSuccess: () => { // เมื่อเพิ่มสำเร็จ ให้ Invalidate cache เพื่อให้ React Query ดึงข้อมูลใหม่ queryClient.invalidateQueries(['doctors']); reset(); setIsModalOpen(false); }, }); // 4. จัดการการลบข้อมูล (Mutation) const deleteDoctorMutation = useMutation({ mutationFn: deleteDoctor, onSuccess: () => { // เมื่อลบสำเร็จ ให้ Invalidate cache เพื่อให้ React Query ดึงข้อมูลใหม่ queryClient.invalidateQueries(['doctors']); }, }); const onSubmit = (data) => { addDoctorMutation.mutate(data); }; const handleDelete = (id) => { if (window.confirm('คุณต้องการลบแพทย์คนนี้หรือไม่?')) { deleteDoctorMutation.mutate(id); } }; if (isLoading) return
| ชื่อ | อีเมล | CRM | สาขา | เบอร์โทรศัพท์ | การดำเนินการ |
|---|---|---|---|---|---|
| {doctor.name} | {doctor.email} | {doctor.crm} | {doctor.specialty} | {doctor.telephone} |