Here's my example:
The problem is input value should be displayed in 2 seconds, but it doesn't. I tried to debug the value and it's undefined, but I can't figure out why.
Appreciate any help.
Here's my example:
The problem is input value should be displayed in 2 seconds, but it doesn't. I tried to debug the value and it's undefined, but I can't figure out why.
Appreciate any help.
well it's seem delayHandler is no a function that take the value as params and send it to debounce you should do like this and it will work:
import React, { useState } from "react";
import "./styles.css";
function debounce(fn, ms, ...args) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, ms);
};
}
export default function App() {
const [value, setValue] = useState("");
const handleChange = e => {
const { value } = e.target;
delayHandler(value)();
};
const delayHandler = v =>
debounce(
value => {
setValue(value);
},
2000,
v
);
return (
<div className="App">
<p>Current value: {value}</p>
<form>
<input value={value} onChange={handleChange} />
</form>
</div>
);
}
so by passing v as argument to debounce it will apply it to fn function.
here full example : code
The root of the issue is that the function returned by debounce does not take any parameters and so when you pass in value to delayHandler it doesn't do anything.
Here is a working example:
const { useState } = React;
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, ms);
};
}
function App() {
const [value, setValue] = useState("");
const handleChange = e => {
const { value } = e.target;
delayHandler(value);
};
const delayHandler = debounce(setValue, 2000);
return (
<div className="App">
<p>Current value: {value}</p>
<form>
<input onChange={handleChange} />
</form>
</div>
);
}
////////////////////////////////////////
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
<!DOCTYPE html>
<html lang="en">
<head>
<title>React App</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
function debounce(fn, ms, ...args) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, ms);
};
}
const delayHandler = value =>
debounce(
value => {
setValue(value);
},
2000,
value
)();
Here is the fix, when you call the debounce function you have to pass value as a parameter, otherwise the args will not contain the val. By the way you don't have to implement this by yourself, you can use lodash debounce https://lodash.com/docs/4.17.15#debounce