I am using React with Typescript. I have a requirement where we have a filters section with DateRangePicker as one field and dropdown of checkboxes as another. Whenever a date range is selected in the calendar and Ok is clicked we have a handler function that gets called which in turn dispatches a redux action and subsequently api request is sent to filter the data based on the selected date range. Similarly when we check or uncheck a checkbox in the second field another handler function gets called which in turn dispatches a redux action and subsequently api request is sent to filter the data based on the checked data. Now, I need to wait 5 seconds for the user after he/she selects the date range and see if the user checks a checkbox within 5 seconds. If yes, I need to just send a single api request instead of two(one for date range selection and one for checkbox selection). This is how my handler functions look like below
const dateChangeHandler = (value: DateRange | null, event: React.SyntheticEvent) => {
setSelectedDateRange(value);
dispatch(fetchFilteredData({ payload: { dateRange: value, selectedTools: selectedTools } }))
}
const selectionChangeHandler = (value: string[]) => {
if (value.length > 0) {
setSelectedTools(value);
dispatch(fetchFilteredData({ payload: { dateRange: selectedDateRange, selectedTools: value } }))
} else {
dispatch(fetchFilteredData({ payload: { dateRange: selectedDateRange, selectedTools: [] } }))
}
};
Any idea how I can proceed further with this? Any help would be much appreciated. Thanks in advance!
You can set a timeout that, 5s later will trigger the dispatch event. Store the timeout ID in a state/ref and clearTimeout in the other input handler:
const [timeoutId, setTimeoutId] = useState(null);
const dateChangeHandler = (value: DateRange | null, event: React.SyntheticEvent) => {
setSelectedDateRange(value);
const _timeoutId = window.setTimeout(() => dispatch(fetchFilteredData({ payload: { dateRange: value, selectedTools: selectedTools } })), 5000)
setTimeoutId(_timeoutId);
}
const selectionChangeHandler = (value: string[]) => {
if (value.length > 0) {
if (timeoutId) {
window.clearTimeout(timeoutId);
setTimeoutId(null);
}
setSelectedTools(value);
dispatch(fetchFilteredData({ payload: { dateRange: selectedDateRange, selectedTools: value } }))
}
...
};