0

I'm having a page with a textbox on (Textfield from fluent UI). I want to update a server stored value every time the user changes the text. I do not want the user to click a separate 'Save' button since that will interfer with the workflow on the page.

Everytime the user changes the text an event is raised with the new text. Simply enough I catch the event and updates the value. However, an event is raised for every character entered creating a lot of events. And if the user types quickly enough, the server will raise an error saying that I can't update the value cause there is already an update going on.

Is there a way to queue function calls? Meaning that I put the changes in a queue and a separate function handles them one after another?

<TextField
   value={info.location}
   onChange={locationChanged}
/>

const locationChanged = React.useCallback(
   (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => {
   // update server here
   },
   []
);
Joakim
  • 114
  • 1
  • 7

1 Answers1

0

You are probably looking for a debounce function. This function will cancel the call if time between previous call and current call is less than a given time.

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

const debounceChange = debounce(locationChanged);


<TextField
   value={info.location}
   onChange={debounceChange}
/>

Rashomon
  • 5,962
  • 4
  • 29
  • 67