Lodash debounce with React Input

后端 未结 7 1449
刺人心
刺人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 (<>
        
      );
    }
    

提交回复
热议问题