Problem:
In the code below, I tried to type "red" continuously and after 2 seconds, "red" appeared in the textbox. Then, after a few seconds, I tried to type "re" continuously. Now, after 2 seconds I got "STACK OVERFLOW DOES NOT ALLOW ME PROVIDE OUTPUT HERE".
Please try it yourself.
import React from 'react';
import { useCallback, useEffect, useState } from 'react';
import './style.css';
export default function App() {
const [inputValue, setInputValue] = useState('');
function debouce(fn) {
let timeout;
return function() {
console.log("final", arguments[0])
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, arguments), 1000);
};
}
const getvalue = debouce(setInputValue);
let a = "";
const handleChange = useCallback((e) => {
const value = e.target.value;
a = a+ value;
console.log('targetvalue', a);
getvalue(a);
}, []);
return (
<div>
<input onChange={handleChange} value={inputValue} />
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen :)</p>
</div>
);
}
Demo link: https://stackblitz.com/edit/react-nh3ty2
Why? Can anyone explain please how to do it correctly as well
UPDATE: i understood that debouce decorator cannot be altered for the required criteria so im changing from below code
function debouce(fn) {
let a = '',
timerid;
return function (e) {
a = a + e;
clearTimeout(timerid);
timerid = setTimeout(function () {
fn.apply(this, [a]);
a = '';
}, 2000);
};
}
to this
function debouce(fn) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), ms);
};
}