S
S
Scott2020-08-01 23:06:40
JavaScript
Scott, 2020-08-01 23:06:40

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

1 answer(s)
R
Roman, 2020-08-02
@g-unit

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>
  );
}

I'm not quite sure what you want to achieve, but it seems to me that it should generally be something like this:
function debounce(fn, ms) {
  return (...args) => {
    setTimeout(() => {
      fn.apply(this, args);
    }, ms);
  };
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question