Last active
October 6, 2022 12:58
-
-
Save nzvtrk/1a444cdf6a86a5a6e6d6a34f0db19065 to your computer and use it in GitHub Desktop.
Memoized debounce using lodash for async fetching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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