Dear Team,
Dear Team I am currently working on implementing a date selector using the DHIS2 CalendarInput
component. However, I am encountering an issue where the selected start and end dates are not being saved when I open the modal, select the dates, and close the modal.
Despite selecting the dates, they do not persist, and the expected behavior of saving the selected dates is not occurring.
Could you please assist in identifying the potential cause of this issue? Specifically, I am unsure whether it is related to the state management, date format handling, or event binding within the code. below is the code
import React, { useState } from 'react';
import { Button, Modal, ModalTitle, ModalContent, ModalActions, ButtonStrip, Box }from '@dhis2/ui';
import { CalendarInput } from '@dhis2/ui';
import { useTimeZoneConversion } from '@dhis2/app-runtime';
const PeriodButton = ({ setPeriod }) => {
const [isOpen, setIsOpen] = useState(false);
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
const { fromClientDate } = useTimeZoneConversion();
// Get current date in server timezone to limit end date selection
const now = fromClientDate();
const maxDate = now.getServerZonedISOString().split('T')[0];
const handleOpen = () => setIsOpen(true);
const handleClose = () => setIsOpen(false);
const handleStartDateSelect = ({ dateCalendarString }) => {
setStartDate(dateCalendarString); // Update start date
};
const handleEndDateSelect = ({ dateCalendarString }) => {
setEndDate(dateCalendarString); // Update end date
};
const handleSave = () => {
// Ensure both start and end date are selected
if (startDate && endDate) {
setPeriod({ startDate, endDate }); // Pass selected period to parent
}
handleClose();
};
return (
<>
<Button onClick={handleOpen} primary>
Select Period
</Button>
{isOpen && (
<Modal position="middle" onClose={handleClose}>
<ModalTitle>Select Period</ModalTitle>
<ModalContent>
<Box minWidth="400px" margin="16px 0">
<CalendarInput
label="Start Date"
calendar="gregory"
date={startDate}
onDateSelect={handleStartDateSelect}
maxDate={maxDate} // Limit start date
/>
</Box>
<Box margin="16px 0">
<CalendarInput
label="End Date"
calendar="gregory"
date={endDate}
onDateSelect={handleEndDateSelect}
maxDate={maxDate} // Limit end date
minDate={startDate} // Prevent selecting an end date before the start date
strictValidation={true} // Ensure end date is not before start date
/>
</Box>
</ModalContent>
<ModalActions>
<ButtonStrip end>
<Button onClick={handleClose} secondary>
Cancel
</Button>
<Button onClick={handleSave} primary disabled={!startDate || !endDate} >
Save </Button>
</ButtonStrip> </ModalActions> </Modal> )}
</>
);
};
export default PeriodButton;
Looking forward to your feedback.