From f24d69034ad9a8fe122e8c2096e8dd3280a07404 Mon Sep 17 00:00:00 2001 From: Gabriele Dal Cengio <39023674+gdalcengio@users.noreply.github.com> Date: Mon, 10 Jun 2024 08:51:45 -0700 Subject: [PATCH] Add debounce to search terms to reduce extra calls (#1126) --- src/components/selectRangeUsePlanPage/index.js | 7 +++++++ src/utils/hooks/useDebounce.js | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 src/utils/hooks/useDebounce.js diff --git a/src/components/selectRangeUsePlanPage/index.js b/src/components/selectRangeUsePlanPage/index.js index 701f1370..365e6b8e 100644 --- a/src/components/selectRangeUsePlanPage/index.js +++ b/src/components/selectRangeUsePlanPage/index.js @@ -9,6 +9,7 @@ import { getDataFromLocalStorage, saveDataInLocalStorage } from '../../utils'; +import useDebounce from '../../utils/hooks/useDebounce'; import Error from './Error'; import { makeStyles } from '@material-ui/core/styles'; import ZoneSelect, { ZoneSelectAll } from './ZoneSelect'; @@ -56,19 +57,25 @@ const useStyles = makeStyles(() => ({ const SelectRangeUsePlanPage = ({ match, history }) => { const { page = 1 } = match.params; + const debouncedPage = useDebounce(page, 500); const [toastId, setToastId] = useState(); const [limit = 10, setLimit] = useQueryParam('limit', StringParam); + const debouncedLimit = useDebounce(limit, 500); const [searchSelectedZones, setSearchSelectedZones] = useState([]); + const debouncedZones = useDebounce(searchSelectedZones, 500); const [orderBy = 'agreement.forest_file_id', setOrderBy] = useQueryParam( 'orderBy', StringParam, ); + const debouncedOrderBy = useDebounce(orderBy, 500); const [order = 'asc', setOrder] = useQueryParam('order', StringParam); + const debouncedOrder = useDebounce(order, 500); const filterInfo = getDataFromLocalStorage("filter-info"); const [filters = { agreementCheck: 'true' }, setFilters] = useQueryParam( 'filters', NewObjectParam, ); + const debouncedFilters = useDebounce(filters, 500); const [filtersInitialized, setFiltersInitialized] = useState(false); // startup useEffect(() => { diff --git a/src/utils/hooks/useDebounce.js b/src/utils/hooks/useDebounce.js new file mode 100644 index 00000000..41e59f86 --- /dev/null +++ b/src/utils/hooks/useDebounce.js @@ -0,0 +1,18 @@ +// useDebounce.js, from https://github.com/vercel/swr/issues/110 +import { useState, useEffect } from 'react'; + +export default function useDebounce(value, delay) { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const handler = setTimeout(() => { + setDebouncedValue(value); + }, delay); + + return () => { + clearTimeout(handler); + }; + }, [value, delay]); + + return debouncedValue; +} \ No newline at end of file