lodash#debounce TypeScript Examples
The following examples show how to use
lodash#debounce.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts From XFlow with MIT License | 7 votes |
onConfigChange = debounce(
config => {
const configChange = getProps('onConfigChange')
if (!configChange || typeof configChange !== 'function') {
return
}
return configChange({
data: getGraphData(),
...config,
})
},
300,
{
trailing: true,
},
)
Example #2
Source File: formikAutoSave.tsx From amplication with Apache License 2.0 | 6 votes |
FormikAutoSave = ({ debounceMS = 1000, onError }: Props) => {
const formik = useFormikContext();
// eslint-disable-next-line react-hooks/exhaustive-deps
const debouncedSubmit = useCallback(
debounce(() => {
return formik
.submitForm()
.then(() => {})
.catch(onError);
}, debounceMS),
[formik.submitForm, debounceMS]
);
useEffect(() => {
if (formik.dirty) {
debouncedSubmit();
}
}, [debouncedSubmit, formik.values, formik.dirty]);
return null;
}
Example #3
Source File: index.ts From S2 with MIT License | 6 votes |
private renderByZoomScale = debounce(
(event: Event & { target: VisualViewport }) => {
const ratio = Math.ceil(event.target.scale);
if (ratio >= 1) {
this.renderByDevicePixelRatio(ratio);
}
},
350,
);
Example #4
Source File: useDataTransfer.ts From easy-email with MIT License | 6 votes |
export function useDataTransfer() {
const { dataTransfer, setDataTransfer } = useContext(HoverIdxContext);
// eslint-disable-next-line react-hooks/exhaustive-deps
const setDataTransferDebounce = useCallback(debounce(setDataTransfer), [
setDataTransfer,
]);
return useMemo(
() => ({
dataTransfer,
setDataTransfer: setDataTransferDebounce,
}),
[dataTransfer, setDataTransferDebounce]
);
}
Example #5
Source File: duration-slider.tsx From backstage with Apache License 2.0 | 6 votes |
export function DurationSlider(props: DurationSliderProps) {
const { header, value, setValue } = props;
const [curValue, setCurValue] = useState(value);
const debouncedSetValue = useMemo(() => debounce(setValue, 1000), [setValue]);
const onChange = useCallback(
(_: any, index: number | number[]) => {
const millis = marks[index as number].seconds * 1000;
setCurValue(millis);
debouncedSetValue(millis);
},
[debouncedSetValue],
);
const indexValue = useMemo(() => findMarkIndex(curValue / 1000), [curValue]);
return (
<>
<Label>
{header} {formatDuration(curValue)}
</Label>
<Slider
value={indexValue}
min={0}
step={1}
max={marks.length - 1}
marks
getAriaValueText={formatDurationFromIndex}
valueLabelFormat={formatDurationFromIndex}
onChange={onChange}
valueLabelDisplay="auto"
aria-labelledby="slider-hide-limit"
/>
</>
);
}
Example #6
Source File: ExampleList.tsx From plugin-vscode with Apache License 2.0 | 6 votes |
constructor(props: SamplesListProps, context: SamplesListState) {
super(props, context);
this.onSearchQueryEdit = debounce(() => {
const { searchQuery } = this.state;
if (searchQuery !== undefined && this.availableSamples) {
let samples = cloneDeep(this.availableSamples);
samples = samples.filter((sampleCategory) => {
if (!sampleCategory.title.toLowerCase().includes(searchQuery)) {
sampleCategory.samples = sampleCategory
.samples.filter((sample) => sample.name.toLowerCase().includes(searchQuery));
}
return sampleCategory.samples.length !== 0;
});
if (samples.length === 0) {
samples = cloneDeep(this.availableSamples);
this.setState({
noSearchReults: true
});
} else {
this.setState({
noSearchReults: false
});
}
this.setState({
samples,
});
}
}, 500).bind(this);
}
Example #7
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
InputFilterItem = ({
itemData,
value,
active,
onVisibleChange,
onChange,
onQuickOperation,
}: IFilterItemProps<'input'>) => {
const { key, placeholder, disabled } = itemData;
const [inputVal, setInputVal] = React.useState(value);
const debouncedChange = React.useRef(debounce(onChange, 1000));
useUpdateEffect(() => {
setInputVal(value);
}, [value]);
useUpdateEffect(() => {
if (inputVal !== value) {
debouncedChange?.current({ key, value: inputVal }, { forceChange: true });
}
}, [inputVal]);
return (
<Input
value={inputVal}
disabled={disabled}
size="small"
style={{ width: 180 }}
allowClear
className="bg-black-06"
prefix={<ErdaIcon fill="default-3" size="16" type="search" />}
placeholder={firstCharToUpper(placeholder)}
onChange={(e) => setInputVal(e.target.value)}
/>
);
}
Example #8
Source File: LocalDeck.ts From excalideck with MIT License | 6 votes |
LocalDeck = {
get(): Deck | null {
try {
const serializedDeck = localStorage.getItem(LOCAL_STORAGE_ITEM_KEY);
return serializedDeck ? JSON.parse(serializedDeck) : null;
} catch {
// Ignore parsing errors, and just fallback to returning null
return null;
}
},
set: debounce((deck: Deck): void => {
localStorage.setItem(LOCAL_STORAGE_ITEM_KEY, JSON.stringify(deck));
}, 2000),
}
Example #9
Source File: useDebounceFn.ts From gio-design with Apache License 2.0 | 6 votes |
function useDebounceFn<T extends Fn>(fn: T, wait = 0, options?: DebounceSettings) {
const debouncedCallback = useMemo(() => debounce(fn, wait, options), [fn, wait, options]);
useEffect(
() => () => {
const callback = debouncedCallback as any;
callback.clear && callback.clear();
},
[debouncedCallback]
);
return debouncedCallback;
}
Example #10
Source File: useDebouncedCallback.ts From jitsu with MIT License | 6 votes |
useDebouncedCallback = <T extends (...args: any[]) => unknown>(
callback: T,
delay: number
): DebouncedFunc<T> => {
// ...
const inputsRef = useRef({ callback, delay })
const isMounted = useIsMounted()
useEffect(() => {
inputsRef.current = { callback, delay }
}, [callback, delay])
return useCallback<DebouncedFunc<T>>(
debounce<T>(
((...args) => {
// Debounce is an async callback. Cancel it, if in the meanwhile
// (1) component has been unmounted (see isMounted in snippet)
// (2) delay has changed
if (inputsRef.current.delay === delay && isMounted()) inputsRef.current.callback(...args)
}) as T,
delay
),
[delay, debounce]
)
}
Example #11
Source File: CredentialGenerator.tsx From jellyfin-audio-player with MIT License | 6 votes |
checkIfCredentialsAreThere = debounce(() => {
// Inject some javascript to check if the credentials can be extracted
// from localstore
this.ref.current?.injectJavaScript(`
try {
let credentials = JSON.parse(window.localStorage.getItem('jellyfin_credentials'));
let deviceId = window.localStorage.getItem('_deviceId2');
window.ReactNativeWebView.postMessage(JSON.stringify({ credentials, deviceId }))
} catch(e) { }; true;
`);
}, 500);
Example #12
Source File: file-watcher.utils.ts From relate with GNU General Public License v3.0 | 6 votes |
setDbmsWatcher = (watchPath: string[]): FSWatcher => {
const watcher = chokidar.watch(watchPath, {
followSymlinks: true,
ignoreInitial: true,
persistent: true,
awaitWriteFinish: true,
});
const fileEventHandler = (eventType: DBMS_EVENT_TYPE.STARTED | DBMS_EVENT_TYPE.STOPPED) => (e: string) => {
if (path.extname(e) === '.pid') {
// determine dbmsId from chokidar event
const dbmsIdCheck = e.match(/dbms-([^/]+)/);
const dbmsId = dbmsIdCheck ? dbmsIdCheck[1] : '';
if (dbmsId) {
pubSub.publish('infoDbmssUpdate', {
dbmsId,
eventType,
});
}
}
};
const dirEventHandler = (eventType: DBMS_EVENT_TYPE.INSTALLED | DBMS_EVENT_TYPE.UNINSTALLED) =>
// debounce for now as multiple events for addDir (different flags)
debounce(
(e: string) => {
// determine dbmsId from chokidar event
// only interested in the top level dir
// so ignore any events with a trailing slash
const dbmsDirIdCheck = e.match(/dbms-([\w-]+[^/]$)/);
const dbmsId = dbmsDirIdCheck ? dbmsDirIdCheck[1] : '';
if (dbmsId) {
pubSub.publish('infoDbmssUpdate', {
dbmsId,
eventType,
});
}
},
500,
{trailing: true},
);
// determine dbms start / stop (add / unlink of pid file respectively)
watcher.on('add', fileEventHandler(DBMS_EVENT_TYPE.STARTED));
watcher.on('unlink', fileEventHandler(DBMS_EVENT_TYPE.STOPPED));
// determine dbms install / uninstall (addDir / unlinkDir of top level DBMS dir respectively)
watcher.on('addDir', dirEventHandler(DBMS_EVENT_TYPE.INSTALLED));
watcher.on('unlinkDir', dirEventHandler(DBMS_EVENT_TYPE.UNINSTALLED));
return watcher;
}
Example #13
Source File: useDateRangeSearch.ts From condo with MIT License | 6 votes |
useDateRangeSearch = <F> (
filterKey: string,
loading: boolean,
): [null | DayJSRangeType, (search: DayJSRangeType) => void] => {
const router = useRouter()
const filtersFromQuery = getFiltersFromQuery<F>(router.query)
const searchValueFromQuery = get(filtersFromQuery, filterKey, null)
const dateRange: DayJSRangeType = isArray(searchValueFromQuery)
? [dayjs(searchValueFromQuery[0]), dayjs(searchValueFromQuery[1])]
: null
const searchChange = useCallback(
debounce(
async (searchString) => {
await updateQuery(router, {
...filtersFromQuery,
[filterKey]: searchString,
})
},
400,
),
[loading, searchValueFromQuery],
)
const handleSearchChange = (value: DayJSRangeType): void => {
searchChange(value)
}
return [dateRange, handleSearchChange]
}
Example #14
Source File: UserSelect.tsx From querybook with Apache License 2.0 | 6 votes |
loadOptions = debounce(
(name, callback) => {
SearchUserResource.search({ name }).then(({ data }) => {
callback(
data.map((user) => ({
value: user.id,
label: <UserSelectOptionRow user={user} />,
name: getUserName(user),
}))
);
});
},
1000,
{
leading: true,
}
)
Example #15
Source File: index.ts From memex with MIT License | 6 votes |
handleGraphEvents = (graphin: Graphin) => {
/**
* 监听window事件
* resize :debounce处理
*/
const handleResizeEvent = debounce(() => {
handleResize(graphin);
}, 100);
window.addEventListener('resize', handleResizeEvent, false);
/**
* 监听wheel/zoom事件
*/
handleZoom(graphin);
/**
* 基于力导的节点拖拽
*/
// dragWithForce(graphin);
/**
* 事件清除
*/
return {
clear: () => {
window.removeEventListener('resize', handleResizeEvent, false);
},
};
}
Example #16
Source File: storyblok.ts From nextjs-bigcommerce-starter with MIT License | 6 votes |
function initEventListeners(story: StoryData, setStory: any) {
if (window.storyblok) {
window.storyblok.init({
accessToken: process.env.STORYBLOK_TOKEN
});
window.storyblok.on(["change", "published"], () => location.reload(true));
const inputFunction = (event: any, s: any) => {
const content = s.content ? s.content : s
if (event && event.story.content._uid === content._uid) {
event.story.content = window.storyblok.addComments(event.story.content, event.story.id)
if(event.story.content.body) {
const mergedBody: any[] = event.story.content.body?.map((item: StoryblokComponent<string>) => {
let oldItem = content.body.find((itemWithData: StoryblokComponent<string>) => itemWithData._uid === item._uid)
return merge(oldItem, item)
}).filter(Boolean)
event.story.content.body = mergedBody
}
setStory(event.story)
}
}
// we will debounce the funcction since we're doing some data processing inside
window.storyblok.on('input', debounce((e) => inputFunction(e, story), 300))
}
}
Example #17
Source File: CompiledCodeContentProvider.ts From language-tools with MIT License | 6 votes |
constructor(private getLanguageClient: () => LanguageClient) {
this.subscriptions.push(
workspace.onDidChangeTextDocument(
debounce(async (changeEvent) => {
if (changeEvent.document.languageId !== 'svelte') {
return;
}
const srcUri = changeEvent.document.uri.toString();
if (this.watchedSourceUri.has(srcUri)) {
this.didChangeEmitter.fire(toSvelteSchemeUri(srcUri));
}
}, 500)
)
);
window.onDidChangeVisibleTextEditors((editors) => {
const previewEditors = editors.filter(
(editor) => editor?.document?.uri?.scheme === SVELTE_URI_SCHEME
);
this.watchedSourceUri = new Set(
previewEditors.map((editor) => fromSvelteSchemeUri(editor.document.uri, true))
);
});
}
Example #18
Source File: DashboardPicker.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
DashboardPicker: FC<Props> = ({
onSelected,
currentDashboard,
size = 'md',
isClearable = false,
invalid,
disabled,
}) => {
const debouncedSearch = debounce(getDashboards, 300, {
leading: true,
trailing: true,
});
const [state, searchDashboards] = useAsyncFn(debouncedSearch, []);
return (
<Forms.AsyncSelect
size={size}
isLoading={state.loading}
isClearable={isClearable}
defaultOptions={true}
loadOptions={searchDashboards}
onChange={onSelected}
placeholder="Select dashboard"
noOptionsMessage="No dashboards found"
value={currentDashboard}
invalid={invalid}
disabled={disabled}
/>
);
}
Example #19
Source File: index.ts From TidGi-Desktop with Mozilla Public License 2.0 | 6 votes |
debouncedSetSettingFile = debounce(async (workspaces: Record<string, IWorkspace>) => {
try {
await settings.set(`workspaces`, workspaces as any);
} catch (error) {
logger.error('Setting file format bad in debouncedSetSettingFile, will try again', { workspaces });
fixSettingFileWhenError(error as Error);
await settings.set(`workspaces`, workspaces as any);
}
}, 500)
Example #20
Source File: fetch.ts From vue-reuse with MIT License | 6 votes |
constructor(
service: Service<R, P>,
config: FetchConfig<R, P>,
subscribe: Subscribe<R, P>,
initResult?: { loading?: boolean; data?: R; params: P }
) {
this.service = service
this.config = config
this.subscribe = subscribe
if (initResult) {
this.result = {
...this.result,
...initResult
}
}
this.debounceRun = this.config?.debounceTime
? debounce(this._run, this.config.debounceTime)
: undefined
this.throttleRun = this.config?.throttleTime
? throttle(this._run, this.config.throttleTime)
: undefined
}
Example #21
Source File: UsernameInput.tsx From frontend.ro with MIT License | 5 votes |
function UsernameInput({ name }: any) {
const ref = useRef<HTMLInputElement>(null);
const checkFn = useRef<DebouncedFunc<(value: string) => void>>(debounce(checkUsername, 250));
const [username, setUsername] = useState(null);
const [usernameExists, setUsernameExists] = useState(undefined);
const onUsernameChange = (e) => {
let value: string = e.target.value ?? '';
value = value.trim();
setUsername(value);
setUsernameExists(undefined);
if (!value) {
return;
}
checkFn.current.cancel();
checkFn.current(value);
};
function checkUsername(value: string) {
return UserService.checkUsername(value)
.then(() => {
setUsernameExists(true);
ref.current.setCustomValidity('Acest username există deja');
})
.catch(() => {
ref.current.setCustomValidity('');
setUsernameExists(false);
});
}
return (
<InputWithIcon
required
type="text"
name={name}
ref={ref}
onChange={onUsernameChange}
>
{usernameExists && <FontAwesomeIcon width="1em" className="text-red" icon={faTimes} />}
{usernameExists === false && <FontAwesomeIcon width="1em" className="text-green" icon={faCheck} />}
{usernameExists === undefined && username && <FontAwesomeIcon width="1em" className="rotate" icon={faSpinner} />}
</InputWithIcon>
);
}
Example #22
Source File: Validation.tsx From symphony-ui-toolkit with Apache License 2.0 | 5 votes |
private debouncedUpdateState = debounce(this.updateState);
Example #23
Source File: base-facet.ts From S2 with MIT License | 5 votes |
delayHideScrollBar = debounce(this.hideScrollBar, 1000);
Example #24
Source File: PreloadImg.tsx From easy-email with MIT License | 5 votes |
on<T extends keyof EventTypeHandles>(type: T, fn: EventTypeHandles[T]) {
this.handler[type].push(debounce(fn, 200));
}
Example #25
Source File: index.tsx From fishbowl with MIT License | 5 votes |
export function LetterInput(props: { value: string }) {
const { t } = useTranslation()
const currentPlayer = React.useContext(CurrentPlayerContext)
const currentGame = React.useContext(CurrentGameContext)
const [updateGameSettings] = useUpdateGameSettingsMutation()
const [textFieldValue, setTextFieldValue] = React.useState(props.value)
const canConfigureSettings = currentPlayer.role === PlayerRole.Host
React.useEffect(() => {
setTextFieldValue(props.value)
}, [props.value])
const debouncedUpdateGameSettings = React.useRef(
debounce((value: string) => {
updateGameSettings({
variables: {
id: currentGame.id,
input: { starting_letter: value },
},
})
}, DEBOUNCE_SECONDS)
).current
return (
<TextField
label={t("settings.cards.letter.label", "Letter")}
variant="outlined"
size="medium"
helperText={
<HelperText>
{currentPlayer.role === PlayerRole.Host ? (
<>
<span>
{t(
"settings.cards.letter.helper",
"One style of play is that all words or phrases must start with the same letter."
)}{" "}
{t("settings.cards.letter.helperHost", "Ask your group!")}
</span>
<br />
<Link
href=""
onClick={(e: React.MouseEvent<HTMLElement>) => {
e.preventDefault()
const randomLetter =
sample(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZ")) || "A"
setTextFieldValue(randomLetter)
debouncedUpdateGameSettings(randomLetter)
}}
>
{t(
"settings.cards.letter.generateRandom",
"Generate random letter"
)}
</Link>
</>
) : (
<span>
{t(
"settings.cards.letter.helper",
"One style of play is that all words or phrases must start with the same letter."
)}{" "}
{t(
"settings.cards.letter.helperPlayers",
"If none is chosen, any word or phrase is fair game!"
)}
</span>
)}
</HelperText>
}
value={textFieldValue}
inputProps={{ maxLength: 1, style: { textTransform: "uppercase" } }}
disabled={!canConfigureSettings}
onChange={({ target: { value } }) => {
setTextFieldValue(value)
debouncedUpdateGameSettings(value)
}}
/>
)
}
Example #26
Source File: GeneralLogin.tsx From next-basics with GNU General Public License v3.0 | 5 votes |
constructor(props: GeneralLoginProps) {
super(props);
const history = getHistory();
const params = new URLSearchParams(history.location.search);
const service = params.get("service");
const featureFlags = getRuntime().getFeatureFlags();
const misc = getRuntime().getMiscSettings();
const lastMethod = this.storage.getItem(lastLoginMethod);
this.loginMethods = misc.enabled_login_types ?? ["easyops"];
this.state = {
loggingIn: false,
service,
imageHeight: window.innerHeight,
loginErrorMsg: "",
currentLoginMethod:
lastMethod && this.loginMethods?.includes(lastMethod)
? lastMethod
: this.loginMethods?.[0] ?? "easyops",
yzm: "",
yzm_value: "",
security_codeEnabled: featureFlags["security-code"],
};
const enabledQRCode = featureFlags["wx-QR-code"];
if (enabledQRCode) {
const { wxAppid, wxAgentid, wxRedirect } = misc;
const canWxQRCodeLogin =
enabledQRCode && wxAppid && wxAgentid && wxRedirect;
this.state = {
...this.state,
wxQRCodeLogin: !!canWxQRCodeLogin,
wxQRCodeOptions: {
appid: wxAppid as string,
agentid: wxAgentid as string,
redirect_uri: encodeURIComponent(wxRedirect as string),
},
};
}
this.onWindowResized = debounce(this.onWindowResized, 500, {
leading: false,
});
}
Example #27
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
PureFilter = (props: IPureFilterProps) => {
const {
filterTirgger = 'onChange',
connectUrlSearch = false,
updateSearch,
onFilter = noop,
query = {},
className = '',
formatFormData,
urlExtra,
...rest
} = props;
// const query = routeInfoStore.getState(s => s.query);
const filterRef: any = React.useRef(null as any);
useMount(() => {
const { pageNo: _, ...fieldsValue } = query;
// 关联url, 将query初始化到表单
if (connectUrlSearch && !isEmpty(fieldsValue)) {
setTimeout(() => {
setFieldsValue(fieldsValue);
}, 0);
} else if (filterTirgger === 'onChange') {
setTimeout(() => {
// 只能在setTimeout中拿到初始请求的值
const formData = filterRef.current?.form.getFieldsValue();
changeFilterData(formData);
}, 0);
}
});
React.useEffect(() => {
if (!isEmpty(urlExtra)) {
const filterForm = get(filterRef, 'current.form');
const filterData = filterForm ? filterForm.getFieldsValue() : {};
updateSearch({ ...urlExtra, ...filterData });
}
}, [updateSearch, urlExtra]);
const debounceFilter = debounce((filterData: Obj) => {
if (connectUrlSearch) {
updateSearch(filterData);
}
onFilter(filterData);
}, 1000);
// filter变化的时候调用
const changeFilterData = (filterData: Obj) => {
debounceFilter(filterData);
};
const setFieldsValue = (obj: Obj) => {
const filterForm = get(filterRef, 'current.form');
if (filterForm) {
const filterFields = filterForm.getFieldsValue();
const formValue = {};
map(filterFields, (_, _key) => has(obj, _key) && set(formValue, _key, obj[_key]));
filterForm.setFieldsValue(formatFormData ? formatFormData(formValue) : formValue);
changeFilterData(obj); // 带上除filter之外的其他参数,如pageNo
}
};
const filterProps = {
onChange: {
actions: [],
},
onSubmit: {},
};
return (
<BaseFilter
onSubmit={changeFilterData}
className={`dice-filter my-3 ${className}`}
{...rest}
{...(filterProps[filterTirgger] || {})}
ref={filterRef}
/>
);
}
Example #28
Source File: index.tsx From gant-design with MIT License | 5 votes |
onSearch = debounce(value => {
const { onSearch, setFilter, getData } = this.props;
setFilter(value);
getData();
onSearch(value);
// this.props.renderList=[]
}, 300);
Example #29
Source File: DruidQueryBuilder.tsx From druid-grafana with Apache License 2.0 | 5 votes |
DruidQueryBuilder = (props: QueryBuilderProps) => {
return (
<Query {...props} onOptionsChange={debounce(props.onOptionsChange, props.options.settings.debounceTime || 250)} />
);
}