Last active
September 14, 2022 13:12
-
-
Save louicoder/f3941d4cf9c7762e1fab389eaa6b04ee to your computer and use it in GitHub Desktop.
Debounce functionality for auto suggestion while typing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function called when debounce executes | |
// Usually this is where you call you external api | |
const onDebounce = () => { | |
console.log('calling api....'); | |
}; | |
// Function that handles on change for your iinput | |
const onValueChanged = (e) => { | |
console.log('changing state....'); | |
setState(e.target.value); | |
}; | |
// function handles delay in execution for your other function debounce | |
const debounce = (func) => { | |
let timer; | |
return function (...args) { | |
const context = this; | |
if (timer) clearTimeout(timer); | |
timer = setTimeout(() => { | |
timer = null; | |
func.apply(context, args); | |
}, 3000); | |
}; | |
}; | |
// Function that is called by input onChange Handler | |
const debounceHandler = React.useCallback(debounce(onDebounce), [<inputValue>]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment