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 understand because lodash is expecting a function. What is the right way to do this and can it be done all inline? I have tried nearly every example thus far on SO to no avail.
search(e){ let str = e.target.value; debounce(this.props.relay.setVariables({ query: str }), 500); },
Here's a simple implementation : import React, { useCallback } from "react"; import { debounce } from "lodash"; const handler = useCallback(debounce(someFunction, 2000), []); const onChange = (event) => { // perform any event related action here handler(); };
Lodash debounce() method is that debounce function mentioned in point 3. In this case, the timer will start running from the last call of the debouncedLogHi() function. After 1500 milliseconds, the function will run.
The debounce function can be passed inline in the JSX or set directly as a class method as seen here:
search: _.debounce(function(e) { console.log('Debounced Event:', e); }, 1000)
Fiddle: https://jsfiddle.net/woodenconsulting/69z2wepo/36453/
If you're using es2015+ you can define your debounce method directly, in your constructor
or in a lifecycle method like componentWillMount
.
Examples:
class DebounceSamples extends React.Component { constructor(props) { super(props); // Method defined in constructor, alternatively could be in another lifecycle method // like componentWillMount this.search = _.debounce(e => { console.log('Debounced Event:', e); }, 1000); } // Define the method directly in your class search = _.debounce((e) => { console.log('Debounced Event:', e); }, 1000) }
With a functional react component try using useCallback
. useCallback
memoizes your debounce function so it doesn't get recreated again and again when the component rerenders. Without useCallback
the debounce function will not sync with the next key stroke.
`
import {useCallback} from 'react'; import _debounce from 'lodash/debounce'; import axios from 'axios'; function Input() { const [value, setValue] = useState(''); const debounceFn = useCallback(_debounce(handleDebounceFn, 1000), []); function handleDebounceFn(inputValue) { axios.post('/endpoint', { value: inputValue, }).then((res) => { console.log(res.data); }); } function handleChange (event) { setValue(event.target.value); debounceFn(event.target.value); }; return <input value={value} onChange={handleChange} /> }
`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With