2

As normal, the input has an onChangeevent to detect change (but by character)

const handleChange = event => {
    setInputValue(event.target.value);
    //When typing "asking" => would be "a" "as" "ask", ....
  };

So what I want to do is when scan a bar code by hardware device into an input, then call an action to server only if have scanned the word completely. The problem here is it listen the input change character by character

React.useEffect(() => {
    if (!!inputValue.length) {
      handleScan();
    }
  }, [inputValue]);

Those code will call handleScan on each character that typing in the input, would end up with many time of calling handleScan(). I expect to call once

Is there any way to wait a bit until the input completely have a word (Ex: "BarCode"), then do an action?

Any help would be appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Minh Kha
  • 1,052
  • 8
  • 13

2 Answers2

2

You can utilize the use-debounce hook npm package.

  import useDebounce from 'use-debounce'

  const [inputValue, setInputValue] = useState('Hello');
  // don't update until a second passes
  const [debouncedValue] = useDebounce(inputValue, 1000);

  const handleChange = event => {
    setInputValue(event.target.value);
    //When typing "asking" => would be "a" "as" "ask", ....
  };

  React.useEffect(() => {
    if (!! debouncedValue.length) {
      handleScan();
    }
  }, [debouncedValue]);
Yatrix
  • 13,361
  • 16
  • 48
  • 78
  • 1
    Thanks a lot. From your advice, I did it using a custom debounce hook, get from the documentation from that package: https://codesandbox.io/s/711r1zmq50 – Minh Kha Sep 21 '20 at 02:30
2

You should implement the debouncing concept to avoid unnecessary API calls.

Debouncing

Debouncing in JavaScript is a practice used to improve browser performance. There might be some functionality on a web page that requires time-consuming computations. If such a method is invoked frequently, it might greatly affect the performance of the browser, as JavaScript is a single-threaded language. Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, that it stalls the performance of the web page.

In other words, it limits the rate at which a function gets invoked.

You can follow the concept of whether using the npm package or creating its own custom function for debouncing.

For your better understanding, you can refer to debounce in React.js which has nice definitions and examples.

Make API call after some period of time(ex. 1000 seconds) when user stops typing to avoid multiple API calls.

akhtarvahid
  • 9,445
  • 2
  • 26
  • 29