Rxjs debounce on react text input component using Subjects does not batch input text on stateless/functional component

后端 未结 2 764
野趣味
野趣味 2021-01-16 06:25

I\'m trying to dive deeper into rxjs and found an issue where the input field I\'m trying to debounce dispatches an event on every keypress, the debounce only holds the outp

2条回答
  •  遥遥无期
    2021-01-16 06:53

    Here is a version as custom Hook as this might be used multiple times in a form and can otherwise clutter your code.

    function useDebounce(time: number, defaultValue: T): [T, (v: T) => void] {
      let [value, setValue] = React.useState(defaultValue);
      let [value$] = React.useState(() => new Subject());
      React.useEffect(() => {
        let sub = value$.pipe(debounceTime(time)).subscribe(setValue);
        return () => sub.unsubscribe();
      }, [time, value$]);
     return [value, (v) => value$.next(v)];
    }
    
    //useage: 
    let [value,setValue] = useDebounce(200,"");
    

提交回复
热议问题