2
0
Files
bot/apps/builder/components/shared/DebouncedInput.tsx

46 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-01-06 16:54:23 +01:00
import { Input, InputProps } from '@chakra-ui/react'
import {
ChangeEvent,
ForwardedRef,
forwardRef,
useEffect,
useState,
} from 'react'
2022-03-09 15:12:00 +01:00
import { useDebounce } from 'use-debounce'
2022-01-06 16:54:23 +01:00
type Props = Omit<InputProps, 'onChange' | 'value'> & {
initialValue: string
onChange: (debouncedValue: string) => void
}
export const DebouncedInput = forwardRef(
(
{ onChange, initialValue, ...props }: Props,
ref: ForwardedRef<HTMLInputElement>
) => {
const [currentValue, setCurrentValue] = useState(initialValue)
2022-03-09 15:12:00 +01:00
const [debouncedValue] = useDebounce(
currentValue,
process.env.NEXT_PUBLIC_E2E_TEST ? 0 : 1000
)
2022-01-06 16:54:23 +01:00
useEffect(() => {
2022-03-09 15:12:00 +01:00
if (debouncedValue === initialValue) return
onChange(debouncedValue)
// eslint-disable-next-line react-hooks/exhaustive-deps
2022-03-09 15:12:00 +01:00
}, [debouncedValue])
2022-01-06 16:54:23 +01:00
2022-03-09 15:12:00 +01:00
const handleChange = (e: ChangeEvent<HTMLInputElement>) =>
setCurrentValue(e.target.value)
2022-01-06 16:54:23 +01:00
return (
<Input
{...props}
ref={ref}
value={currentValue}
onChange={handleChange}
/>
)
}
)