Bug on DatePicker and TimePicker on MERN Stack
Hello!
I am facing an issue… When I book appointment, the details are sent. The information is showing up in mongoDB.
Everything is getting recorded but the timings and dates are not getting recorded correctly.
Whatever time & date I enter on the booking page of that doctor, the mongoDB only records time as 00:00 and date as current date.
Can you help me please??
The client code:
function BookAppoiment() {
const [esteDisponibil, setEsteDisponibil] = useState(false);
const navigate = useNavigate();
const [date, setDate] = useState();
const [ora, setOra] = useState();
const params = useParams();
const dispatch = useDispatch();
const [doctor, setDoctor] = useState(null);
const { user } = useSelector((state) => state.user);
const getDoctorData = async () => {
try {
dispatch(showLoading());
const response = await axios.post(
'/api/doctor/get-doctor-info-by-id',
{ doctorId: params.doctorId },
{
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
}
);
dispatch(hideLoading());
if (response.data.success) {
setDoctor(response.data.data);
}
} catch (error) {
console.log(error);
dispatch(hideLoading());
}
};
const checkAvailability = async () => {
if (date && ora) {
try {
dispatch(showLoading());
const response = await axios.post(
'/api/user/check-booking-availability',
{
doctorId: params.doctorId,
date: date,
ora: ora,
},
{
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
}
);
dispatch(hideLoading());
if (response.data.success) {
toast.success(response.data.message);
setEsteDisponibil(true);
} else {
toast.error(response.data.message);
}
} catch (error) {
toast.error('Ceva nu a mers bine la verificarea disponibilității!');
dispatch(hideLoading());
}
}
};
const bookNow = async () => {
setEsteDisponibil(false);
try {
dispatch(showLoading());
const response = await axios.post(
'/api/user/book-appointment',
{
doctorId: params.doctorId,
userId: user._id,
doctorInfo: doctor,
userInfo: user,
date: date,
ora: ora,
},
{
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
}
);
dispatch(hideLoading());
if (response.data.success) {
toast.success(response.data.message);
navigate('/appointments');
}
} catch (error) {
toast.error('Ceva nu a mers bine la crearea programării!');
dispatch(hideLoading());
}
};
useEffect(() => {
getDoctorData();
}, []);
return (
<Layout>
{doctor && (
<div>
<h1 className="page-title">
{doctor.numeDoctor} {doctor.prenumeDoctor}
</h1>
<hr />
<Row gutter={20} className="mt-5" align="middle">
<Col span={12} sm={24} xs={24} lg={8}>
<h1 className="normal-text">
<b>Ore de lucru medic ales: </b>
{doctor.oreLucru[0]} - {doctor.oreLucru[1]}
</h1>
<div className="d-flex flex-column pt-2 mt-2">
{/* <DatePicker
format="DD-MM-YYYY"
onChange={(value) => {
setDate(moment(value).format("DD-MM-YYYY"));
setEsteDisponibil(false);
}}
/>
<TimePicker
format="HH:mm"
className="mt-3"
onChange={(value) => {
setEsteDisponibil(false);
setOra(moment(value).format("HH:mm"));
}}
/> */}
<DatePicker
format="DD-MM-YYYY"
onChange={(value) => {
const formattedDate = value ? moment(value).format("DD-MM-YYYY") : null;
setDate(formattedDate);
setEsteDisponibil(false);
}}
/>
<TimePicker
format="HH:mm"
className="mt-3"
onChange={(value) => {
const formattedTime = value ? moment(value).format("HH:mm") : null;
setOra(formattedTime);
setEsteDisponibil(false);
}}
/>
{!esteDisponibil && (
<Button
className="butonPrincipal mt-3 full-width-buton"
onClick={checkAvailability}
>
Verifică disponibilitatea
</Button>
)}
{esteDisponibil && (
<Button
className="butonPrincipal mt-3 full-width-buton"
onClick={bookNow}
>
Programează-te
</Button>
)}
</div>
</Col>
</Row>
</div>
)}
</Layout>
);
}
export default BookAppoiment;
The server code:
router.post('/book-appointment', authMiddleware, async (req, res) => {
try {
req.body.status = "pending";
req.body.date = moment(req.body.date, 'DD-MM-YYYY').format('YYYY-MM-DD');
req.body.ora = moment(req.body.ora, 'HH:mm').format('HH:mm:ss');
const newAppointment = new Appointment(req.body);
await newAppointment.save();
// Send notifications to the doctor based on their userId
const user = await User.findOne({ _id: req.body.doctorInfo.userId });
user.unseenNot.push({
type: "new-appointment-request",
message: `Pacientul ${req.body.userInfo.nume} ${req.body.userInfo.prenume} a făcut o nouă cerere de programare`,
onClickPath: '/doctor/appointments',
});
await user.save();
res.status(200).send({
message: "Programare făcută cu succes!",
success: true,
});
} catch (error) {
console.log(error);
res.status(500).send({
message: "Eroare la crearea programarii",
success: false,
error,
});
}
});
router.post('/check-booking-availability', authMiddleware, async (req, res) => {
try {
const date = moment(req.body.date, 'DD-MM-YYYY').toISOString();
const fromTime = moment(req.body.ora, "HH:mm").subtract(1, 'hours').toISOString();
const toTime = moment(req.body.ora, "HH:mm").add(1, 'hours').toISOString();
const doctorId = req.body.doctorId;
const appointments = await Appointment.find({
doctorId,
date,
ora: { $gte: fromTime, $lte: toTime },
});
if (appointments.length > 0) {
return res.status(200).send({
message: "Doctorul nu este disponibil pentru acea oră!",
success: false,
});
} else {
return res.status(200).send({
message: "Doctorul este disponibil pentru acea oră!",
success: true,
});
}
} catch (error) {
console.log(error);
res.status(500).send({
message: "Eroare la verificarea disponibilității programării!",
success: false,
error,
});
}
});