0

I have a simpel form:

https://codesandbox.io/s/distracted-poincare-2blfq?file=/src/App.js:357-552

      <form>
        <TextField
          onChange={handleChange}
          onBlur={clearInput}
          value={inputValue}
          placeholder="Do an api request"
        />
      </form>

On the onChange I want to do an api request with the value of the input but I would like to add a debounce or throttle. Important is that when the input is blurred the text in the input should be removed and the placeholder should be visible.

Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185

1 Answers1

0

Method 1.

Use React debounce input, simple method

https://www.npmjs.com/package/react-debounce-input

Method 2

Create timer and call API based on that, no external library needed. and i always suggest this

 let timer = null
 const handleChange = (e) => {
    setInputValue(e.target.value)
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(()=>yourApiCall(e.target.value), 700)
 }
 const yourApiCall = (val) => {
   //call API here
 }

  <form>
    <TextField
      onChange={handleChange}
      onBlur={clearInput}
      value={inputValue}
      placeholder="Do an api request"
    />
  </form>

a working example

https://codesandbox.io/s/beautiful-goldberg-vyo2u?file=/src/App.js

Method 3

Use loadash debounce

check the answers from this link

Lodash debounce with React Input

sojin
  • 2,158
  • 1
  • 10
  • 18