Awesome Debounce Promise
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 = ; const asyncFunctionDebounced = ;
Usecases
Debouncing a search input
const searchAPI = ; const searchAPIDebounced = ; Component state = text: '' results: null ; handleTextChange = async { this; const result = await ; this; }; { this {}; }
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 ; const saveFieldValueDebounced = ; Component state = value1: '' value2: '' ; onFieldTextChange = this; await ; ; { const value1 value2 = thisstate; return <form> <input = = /> <input = = /> </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 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 { const searchAPI = ; const searchAPIDebounced = ; this; const result = await ; this;};
Do this:
const searchAPI = ;const searchAPIDebounced = ; handleTextChange = async { this; const result = await ; this;};
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.