JustFly1984 / react-google-maps-api

React Google Maps API
MIT License
1.76k stars 426 forks source link

How to add debounce in AutoComplete #3169

Closed Risyandi closed 1 year ago

Risyandi commented 1 year ago

how to add debounce at best places (onload, onPlaceChanged, or etc) in Autocomplete using this function for example debounce.

function debounce(func, timeout = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  };
}

Environment

os: windows

react version : 16.13.1

@react-google-maps/api version : 1.8.9

JustFly1984 commented 1 year ago

you should wrap the function you pass into useCallback hook.

{
const debouncedOnClick = useCallback(
  debounce(() => { 
    /* your code goes here */ 
  }, 400), 
  [/* do not forget to set dependencies for your code*/]
)

...
}
Risyandi commented 1 year ago

Hi, @JustFly1984 Thank you for your response, I will try the solution. hopefully will be working fine.