visus-plus/web-app/src/hooks/data/usePatients.js

78 lines
2.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useDispatch, useSelector } from "react-redux";
import { notification } from "antd";
import {
useAddPatientMutation,
useDeletePatientMutation,
useGetPatientsQuery,
useUpdatePatientMutation
} from "../../redux/services/patientsApi.js";
import {closeModal} from "../../redux/slices/patientsSlice.js";
const usePatients = () => {
const dispatch = useDispatch();
const {
selectedPatient,
} = useSelector(state => state.patientsUI);
const { data: patients = [], isLoading, isError } = useGetPatientsQuery(undefined, {
pollingInterval: 20000,
});
const [addPatient] = useAddPatientMutation();
const [updatePatient] = useUpdatePatientMutation();
const [deletePatient] = useDeletePatientMutation();
const handleDeletePatient = async (patientId) => {
try {
await deletePatient(patientId).unwrap();
notification.success({
message: "Пациент удалён",
description: "Пациент успешно удалён из базы.",
placement: "topRight",
});
} catch (error) {
notification.error({
message: "Ошибка удаления",
description: error.data?.message || "Не удалось удалить пациента",
placement: "topRight",
});
}
};
const handleModalSubmit = async (patientData) => {
dispatch(closeModal());
try {
if (selectedPatient) {
await updatePatient({ id: selectedPatient.id, ...patientData }).unwrap();
notification.success({
message: "Пациент обновлён",
description: `Данные пациента ${patientData.first_name} ${patientData.last_name} успешно обновлены.`,
placement: "topRight",
});
} else {
await addPatient(patientData).unwrap();
notification.success({
message: "Пациент добавлен",
description: `Пациент ${patientData.first_name} ${patientData.last_name} успешно добавлен.`,
placement: "topRight",
});
}
} catch (error) {
notification.error({
message: "Ошибка",
description: error.data?.message || "Произошла ошибка при сохранении",
placement: "topRight",
});
}
};
return {
patients,
isLoading,
isError,
handleDeletePatient,
handleModalSubmit,
};
};
export default usePatients;