npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

awesome-debounce-promise

v2.1.0

Published

Debounce your async calls

Downloads

275,870

Readme

Awesome Debounce Promise

NPM Build Status

Debounce your async calls with React in mind.

Forget about:

  • concurrency issues when promise resolves in "unexpected" order
  • leaving promise land for callback hell of Lodash / Underscore

From the author of this famous SO question about debouncing with React.

Install

yarn add awesome-debounce-promise

npm install awesome-debounce-promise --save

import AwesomeDebouncePromise from 'awesome-debounce-promise';

const asyncFunction = () => fetch('/api');

const asyncFunctionDebounced = AwesomeDebouncePromise(
  asyncFunction,
  500,
  options,
);

Usecases

Debouncing a search input

const searchAPI = text => fetch('/search?text=' + encodeURIComponent(text));

const searchAPIDebounced = AwesomeDebouncePromise(searchAPI, 500);

class SearchInputAndResults extends React.Component {
  state = {
    text: '',
    results: null,
  };

  handleTextChange = async text => {
    this.setState({ text, results: null });
    const result = await searchAPIDebounced(text);
    this.setState({ result });
  };

  componentWillUnmount() {
    this.setState = () => {};
  }
}

When calling debouncedSearchAPI:

  • it will debounce the api calls. The API will only be called when user stops typing
  • each call will return a promise
  • only the promise returned by the last call will resolve, which will prevent the concurrency issues
  • there will be at most a single this.setState({ result }); call per api call

Debouncing the background saving of some form inputs

const saveFieldValue = (fieldId, fieldValue) =>
  fetch('/saveField', {
    method: 'PUT',
    body: JSON.stringify({ fieldId, fieldValue }),
  });

const saveFieldValueDebounced = AwesomeDebouncePromise(
  saveFieldValue,
  500,
  // Use a key to create distinct debouncing functions per field
  { key: (fieldId, text) => fieldId },
);

class SearchInputAndResults extends React.Component {
  state = {
    value1: '',
    value2: '',
  };

  onFieldTextChange = async (fieldId, fieldValue) => {
    this.setState({ [fieldId]: fieldValue });
    await saveFieldValueDebounced(fieldId, fieldValue);
  };

  render() {
    const { value1, value2 } = this.state;
    return (
      <form>
        <input
          value={value1}
          onChange={e => onFieldTextChange(1, e.target.value)}
        />
        <input
          value={value2}
          onChange={e => onFieldTextChange(2, e.target.value)}
        />
      </form>
    );
  }
}

Thanks to the key feature, the 2 fields will be debounced independently from each others. In practice, one debounced function is created for each key.

Options

const DefaultOptions = {
  // One distinct debounced function is created per key and added to an internal cache
  // By default, the key is null, which means that all the calls
  // will share the same debounced function
  key: (...args) => null,

  // By default, a debounced function will only resolve
  // the last promise it returned
  // Former calls will stay unresolved, so that you don't have
  // to handle concurrency issues in your code
  // Setting this to false means all returned promises will resolve to the last result
  onlyResolvesLast: true,
};

Other debouncing options are available and provided by an external low-level library: debounce-promise

FAQ

How can I cancel the debouncing?

You can easily add promise cancellation support to this lib with awesome-imperative-promise, lib that is already used internally.

Why is my debouncing function always firing and is not debounced?

The debouncing function returned by the lib is stateful. If you want deboucing to work fine, make sure to avoid recreating this function everytime. This is the same behavior as regular callback-based debouncing functions.

Instead of this:

handleTextChange = async text => {
  const searchAPI = text => fetch('/search?text=' + encodeURIComponent(text));
  const searchAPIDebounced = AwesomeDebouncePromise(searchAPI, 500);
  this.setState({ text, results: null });
  const result = await searchAPIDebounced(text);
  this.setState({ result });
};

Do this:

const searchAPI = text => fetch('/search?text=' + encodeURIComponent(text));
const searchAPIDebounced = AwesomeDebouncePromise(searchAPI, 500);

handleTextChange = async text => {
  this.setState({ text, results: null });
  const result = await searchAPIDebounced(text);
  this.setState({ result });
};

Hire a freelance expert

Looking for a React/ReactNative freelance expert with more than 5 years production experience? Contact me from my website or with Twitter.