javascripthyperapp

Debounced action on input element's input event in Hyperapp


I'm trying to debounce (using lodash.debounce) an action in a Hyperapp component as the user is typing in a search field. While the actions are delayed, they seem to be queued and will all execute individually when the interval (500 ms) has passed, instead of being skipped altogether.

In other words: if the user types "foo" within 500 ms, it will execute three times, with each individual function call delayed by 500 ms, instead of executing just once.

I've used debounce numerous times in non-Hyperapp contexts, so it feels like I'm missing something in how Hyperapp works.

export default ({ state, actions }) => {
  const debouncedFetchResults = debounce(actions.fetchResults, 500);

  return (
    <input
      type="search"
      name="search"
      value={state.searchPhrase}
      oninput={
        (e) => {
          // Set `state.searchPhrase`
          actions.setSearchPhrase(e.target.value);

          // Search using `state.searchPhrase`
          debouncedFetchResults();
        }
      } />
  );
};

Solution

  • I eventually fixed this issue, using the below method:

    const debouncedFetchResults = debounce(fn => fn(), 500);
    
    export default ({ state, actions }) => (
      <input
        type="search"
        name="search"
        value={state.searchPhrase}
        oninput={
          (e) => {
            // Set `state.searchPhrase`
            actions.setSearchPhrase(e.target.value);
    
            // Search using `state.searchPhrase`
            debouncedFetchResults(actions.fetchResults);
          }
        } />
    );