I'm trying to wait 2 seconds when an input text contains text and make a request to my API. I wrote this function as a react hook called useBounce:
const useDebounce = (func, milliseconds) => {
const time = milliseconds || 400
let timer
return event => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(func, time, event)
}
}
export default useDebounce
So I have an input with an onChange that when I try to write react it doesn't allow me to do it and the call function to my API doesn't execute:
const searchDebounce = useDebounce((e) => {
setInput(e.target.value);
e.preventDefault()
console.log(e.target.value)
}, 2000)
return (
<>
<input
type="text"
onChange={ searchDebounce }
value={input}
className='border-2 border-cyan-500'
/>
</>
)
For now I am trying to see what is written in the input through the console but since it does not allow me to write, the console is blank.
Thanks for your help.
CodePudding user response:
it works with your code with minor changes, i dont know the exact why tho
const useDebounce = (func, milliseconds) => {
const time = milliseconds || 400;
let timer;
return (event) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(func, time, event.target?.value);
};
};
const [input, setInput] = useState('');
const searchDebounce = useDebounce((e) => {
setInput(e);
}, 2000);
return (
<>
<input
type="text"
onChange={searchDebounce}
className="border-2 border-cyan-500"
/>
</>
);
the thing is, if you want to implement debounce function to search something by your input, you shouldn't debounce the the function to update input state (setInput
), since it will also delay the text input value when user is typing in.
CodePudding user response:
Below is the example for same
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value]);
return debouncedValue;
};
the above is my custom useDebounce
hook and to delay the input check below code
export const Debouncing = () => {
const [value, setValue] = useState("");
const delayedValue= useDebounce(value, 2000);
// useEffect(()=>{
//apiCall() api call goes here
//},[delayedValue]);
return (
<>
<h1>Debouncing</h1>
Current: {value} - Debounced: {delayedValue}
<input
value={value}
onChange={(e) => setValue(e.target.value)}
style={{ margin: "30px" }}
placeholder="input search"
/>
</>
);
};