From 1a572138d09d981e6d3800f6da2e5021cb76b7e1 Mon Sep 17 00:00:00 2001 From: Amit Amrutiya Date: Fri, 18 Oct 2024 13:57:20 +0530 Subject: [PATCH] fix: debouncing Signed-off-by: Amit Amrutiya --- .../StyledSearchBar/StyledSearchBar.tsx | 45 +++++++++++++------ 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/src/custom/StyledSearchBar/StyledSearchBar.tsx b/src/custom/StyledSearchBar/StyledSearchBar.tsx index 165f72c2..da529de6 100644 --- a/src/custom/StyledSearchBar/StyledSearchBar.tsx +++ b/src/custom/StyledSearchBar/StyledSearchBar.tsx @@ -1,6 +1,6 @@ import { SxProps, Theme } from '@mui/material'; import { debounce } from 'lodash'; -import React, { useCallback, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { InputAdornment } from '../../base'; import { SearchIcon } from '../../icons'; import { useTheme } from '../../theme'; @@ -14,6 +14,7 @@ interface SearchBarProps { placeholder?: string; sx?: SxProps; endAdornment?: React.ReactNode; + debounceTime?: number; } /** @@ -26,6 +27,7 @@ interface SearchBarProps { * @param {string} [props.placeholder] - The placeholder text for the search input. * @param {Object} [props.sx] - The style object for the search input. * @param {React.ReactNode} [props.endAdornment] - The element to display at the end of the search input. + * @param {number} [props.debounceTime] - The debounce time for the input change handler. * * @returns {JSX.Element} The rendered StyledSearchBar component. */ @@ -35,25 +37,40 @@ function StyledSearchBar({ label, sx, placeholder, - endAdornment + endAdornment, + debounceTime = 300 }: SearchBarProps): JSX.Element { const theme = useTheme(); - const [inputValue, setInputValue] = useState(value); + const [inputValue, setInputValue] = useState(value ?? ''); - const debouncedOnChange = useCallback( - (event: React.ChangeEvent) => { - debounce(() => { - if (onChange) { - onChange(event); - } - }, 300)(); - }, - [onChange] - ); + useEffect(() => { + if (value !== undefined && value !== inputValue) { + setInputValue(value); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [value]); + + useEffect(() => { + const handler = debounce((newValue: string) => { + if (onChange) { + const syntheticEvent = { + target: { value: newValue }, + persist: () => {} + } as React.ChangeEvent; + + onChange(syntheticEvent); + } + }, debounceTime); + + handler(inputValue); + + return () => { + handler.cancel(); + }; + }, [inputValue, onChange, debounceTime]); const handleChange = (event: React.ChangeEvent) => { setInputValue(event.target.value); - debouncedOnChange(event); }; return (