[英]Debounce react-select graphql query
我正在尝试消除我的 react-select 组件发送的 graphql 查询。 我使用的是 wonka 而不是 rxjs 但没有 wonka 的标签。
const GraphqlQueryAsync = (query, outputFn) => (value) => {
console.log({ value });
return pipe(
fromValue(value),
// debounce(() => 5000),
mergeMap((input) => client.executeQuery(createRequest(query, { input }))),
map(outputFn),
take(1),
toPromise,
);
};
React-select 有一个调用我的 graphql 查询的 loadOptions 函数。
<AsyncSelect
defaultValue={value}
styles={selectStyles(error)}
placeholder={title}
onChange={onChangeSelect(onChange, name, lefts)}
defaultOptions
loadOptions={GraphqlQueryAsync(query, outputFn)}
/>
我的功能有效。 然而,随着debounce
,它等待5secs,仍然发送的每个值的变化。 (即,如果我输入“rent”,它会搜索“r”、“re”、“ren”和“rent”)。 我相信这是因为 react-select 重复调用loadOptions
函数,创建多个 Graphql 查询。 无论如何,是否允许 loadOptions 继续将新值传递给带有去抖动功能的GraphqlQueryAsync
函数(即仅发送“租用”搜索词)?
以下是延迟1000
毫秒的函数去抖动的方法:
let timerId = null
const loadOptionsDebounced = (query, outputFn) => {
clearTimeout(timerId)
timerId = setTimeout(() => {
GraphqlQueryAsync(query, outputFn)
}, 1000)
}
在您选择的组件中:
<AsyncSelect
loadOptions={loadOptionsDebounced(query, outputFn)}
</AsyncSelect>
我能够使用 loadOptions 的回调功能解决。
let _GraphqlQueryDebounce;
const GraphqlQueryAsync = (query, outputFn) => (value, callback) => {
console.log({ value });
if(_GraphqlQueryDebounce) clearTimeout(_GraphqlQueryDebounce);
_GraphqlQueryDebounce = setTimeout(async () => callback(
await pipe(
fromValue(value),
mergeMap((input) => client.executeQuery(createRequest(query, { input }))),
map(outputFn),
take(1),
toPromise,
)
), 5000);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.