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

后端 未结 2 758
野趣味
野趣味 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<T = any>(time: number, defaultValue: T): [T, (v: T) => void] {
      let [value, setValue] = React.useState<T>(defaultValue);
      let [value$] = React.useState(() => new Subject<T>());
      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,"");
    
    0 讨论(0)
  • 2021-01-16 07:04

    React continuously calls your function to render the component. Therefore the Subject is continuously recreated.

    Using a factory with useState to keep the subject and working with useEffect to make sure the subscription is only made once should fix your issue.

    Something like this :

    import React, { Component, useState, useEffect, useRef } from 'react';
    import { render } from 'react-dom';
    import { debounceTime, map, tap, distinctUntilChanged } from 'rxjs/operators';
    import { fromEvent, Subject } from 'rxjs';
    
    import './style.css';
    const App = props => {
      const [queryName, setQueryName] = useState("");
      const [debouncedName, setDebouncedName] = useState("");
      const [onSearch$] = useState(()=>new Subject());
      useEffect(() => {
        const subscription = onSearch$.pipe(
          debounceTime(400),
          distinctUntilChanged(),
          tap(a => console.log(a))
        ).subscribe(setDebouncedName);
      }, [])
      const handleSearch = e => {
        setQueryName(e.target.value);
        onSearch$.next(e.target.value);
      };
    
      return (
        <div>
          <input
            placeholder="Search Tags"
            value={queryName}
            onChange={handleSearch}
          />
          <p>Debounced: {debouncedName}</p>
        </div>
      );
    }
    
    render(<App />, document.getElementById('root'));
    
    0 讨论(0)
提交回复
热议问题