Answer the question
In order to leave comments, you need to log in
Why is debounce not working?
After 2 seconds, the value from the input should be displayed, but for some reason it is undefined.
Code here
Answer the question
In order to leave comments, you need to log in
understand (below working code):
import React, { useState } from 'react';
import './styles.css';
function debounce(fn, ms, ...args) {
let timer;
return (value) => {
timer = setTimeout(() => {
// ваш вариант вообще забывал о том что в fn вы пытаетесь передать value
fn.apply(this, [value,...args]);
// удалять обработчик таймаута вообще не надо, но если это всетаки делать, то наверное уже после того как
clearTimeout(timer);
timer = null;
}, ms);
};
}
export default function App() {
const [value, setValue] = useState('');
const handleChange = e => {
const {value} = e.target;
delayHandler(value);
};
const delayHandler = debounce(value=>{
setValue(value);
alert(value);
}, 2000);
return (
<div className="App">
<p>Current value: {value}</p>
<form>
<input onChange={handleChange} />
</form>
</div>
);
}
function debounce(fn, ms) {
return (...args) => {
setTimeout(() => {
fn.apply(this, args);
}, ms);
};
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question