Home > OS >  why this onChange method has invoked several times(infinity) and how to fix this?
why this onChange method has invoked several times(infinity) and how to fix this?

Time:06-20

actually, I am new to React and I am trying to put debouncing along with the event method(onChange) in input to make the code optimized, but when the event occurs instead of calling the function for one time it calls several times(up to infinity).

import { useRef } from "react";
import "./styles.css";

export default function App() {

  var input_ref = useRef(null)
  
//.............Debouncing........................................................

  var debouncing = (callback,threshold)=>{
    var timer;
    return function(){
        const context = this

        if(timer)clearTimeout(timer);
        timer = setInterval(()=>{
            timer = null;
            callback.apply(context);
            //callback()
        },threshold);
    }
}

//........EventHandler with Debouncing............................................

var search_data = debouncing(()=>{
    console.log(input_ref.current.value)
},300)

  return (
    <div className="App">
      <input type="text" name='searchBox' placeholder="search" ref={input_ref} onChange={search_data}/>
    </div>
  );
}

link (CodeSandbox):- https://codesandbox.io/s/debouncing-testing-gxc031?file=/src/App.js

CodePudding user response:

Haha dude, your code works fine except a little bit carelessness: it should be setTimeout instead of setInterval at line 14 :P

CodePudding user response:

First, you use setInterval instead of setTimeout. Second, the debounce function doesn't work fine, I just rewrote it for you, Also it would be better to move it outside the component function, please check the code below it's working as required.

https://codesandbox.io/s/debouncing-testing-forked-ig9vbf

  • Related