Lodash debounce with React Input

后端 未结 7 1450
刺人心
刺人心 2021-02-05 04:54

I\'m trying to add debouncing with lodash to a search function, called from an input onChange event. The code below generates a type error \'function is expected\', which I unde

相关标签:
7条回答
  • 2021-02-05 05:30

    That's not so easy question

    On one hand to just work around error you are getting, you need to wrap up you setVariables in the function:

     search(e){
      let str = e.target.value;
      _.debounce(() => this.props.relay.setVariables({ query: str }), 500);
    }
    

    On another hand, I belive debouncing logic has to be incapsulated inside Relay.

    0 讨论(0)
  • 2021-02-05 05:39
    class MyComp extends Component {
      debounceSave;
      constructor(props) {
        super(props);
      }
      this.debounceSave = debounce(this.save.bind(this), 2000, { leading: false, trailing: true });
    }
    

    save() is the function to be called

    debounceSave() is the function you actually call (multiple times).

    0 讨论(0)
  • 2021-02-05 05:46

    @Aximili

    const [debouncedCallApi] = useState(() => _.debounce(callApi, 1000));
    

    looks strange :) I prefare solutions with useCallback:

    const [searchFor, setSearchFor] = useState('');
    
    const changeSearchFor = debounce(setSearchFor, 1000);
    const handleChange = useCallback(changeSearchFor, []);
    
    0 讨论(0)
  • 2021-02-05 05:48

    This worked for me:

    handleChange(event) {
      event.persist();
      const handleChangeDebounce = _.debounce((e) => {
        if (e.target.value) {
          // do something
        } 
      }, 1000);
      handleChangeDebounce(event);
    }
    
    0 讨论(0)
  • 2021-02-05 05:51

    This is how I had to do it after googling the whole day.

    const MyComponent = (props) => {
      const [reload, setReload] = useState(false);
    
      useEffect(() => {
        if(reload) { /* Call API here */ }
      }, [reload]);
    
      const callApi = () => { setReload(true) }; // You might be able to call API directly here, I haven't tried
      const [debouncedCallApi] = useState(() => _.debounce(callApi, 1000));
    
      function handleChange() { 
        debouncedCallApi(); 
      }
    
      return (<>
        <input onChange={handleChange} />
      </>);
    }
    
    0 讨论(0)
  • for your case, it should be:

    search = _.debounce((e){
     let str = e.target.value;
     this.props.relay.setVariables({ query: str });
    }, 500),
    
    0 讨论(0)
提交回复
热议问题