Skip to content

Instantly share code, notes, and snippets.

@nzvtrk
Last active October 6, 2022 12:58
Show Gist options
  • Save nzvtrk/1a444cdf6a86a5a6e6d6a34f0db19065 to your computer and use it in GitHub Desktop.
Save nzvtrk/1a444cdf6a86a5a6e6d6a34f0db19065 to your computer and use it in GitHub Desktop.
Memoized debounce using lodash for async fetching
import { debounce } from 'lodash';
import axios from 'axios';
// or vanilla debounce
// const debounce = (func, timeOut) => {
// let timer
//
// return (...args) => {
// if (timer) clearTimeout(timer)
// timer = setTimeout(func, timeOut)
// return timer
// }
// }
const getDebouncedByType = (func, wait, options) => {
const memory = {};
return (...args) => {
// use first argument as a key
// its possible to use all args as a key - e.g JSON.stringify(args) or hash(args)
const [searchType] = args;
if (typeof memory[searchType] === 'function') {
return memory[searchType](...args);
}
memory[searchType] = debounce(func, wait, { ...options, leading: true }); // leading required for return promise
return memory[searchType](...args);
};
};
const getAsyncData = (someKind) => {
return axios.get(`/api/${someKind}/list/`);
};
const debouncedGetAsyncData = getDebouncedByType(getAsyncData, 1000);
await debouncedGetAsyncData('cats')
await debouncedGetAsyncData('dogs')
await debouncedGetAsyncData('cats')
await debouncedGetAsyncData('dogs')
await debouncedGetAsyncData('cats')
// return cats list one second after last function call, only one time
// return dogs list one second after last function call, only one time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment