React Native: using lodash debounce

I play with React Native and lodash debounce.

Using the following code only makes it work as a delay, not a dump.

<Input onChangeText={(text) => { _.debounce(()=> console.log("debouncing"), 2000)() } /> 

I want the console to register debounce only once if I enter an input like "foo". Now he registers "debounce" 3 times.

+16
source share
2 answers

The Debounce function must be defined somewhere outside the render method, because it must reference the same instance of the function every time you call it as opposed to creating a new instance, as it is now when you put it in the onChangeText handler.

The most common place to define the debounce function is directly on the component object. Here is an example:

 class MyComponent extends React.Component { constructor() { this.onChangeTextDelayed = _.debounce(this.onChangeText, 2000); } onChangeText(text) { console.log("debouncing"); } render() { return <Input onChangeText={this.onChangeTextDelayed} /> } } 
+56
source

Here you can find a good example of how to use it:

 import React, { useState } from 'react'; import _ from 'lodash'; import { fetchData } from '../../services/request'; import ResultListComponent from '../ResultList'; const SearchBarComponent = () => { const [query, setQuery] = useState(''); const [searchQuery, setSearchQuery] = useState({}); const [dataList, setDataList] = useState([]); const [errorMssg, setErrorMssg] = useState(''); /** * This will be called every time there is * a change in the input * @param {*} { target: { value } } */ const onChange = ({ target: { value } }) => { setQuery(value); // Here we set search var, so debounce will make sure to trigger // the event every 300ms const search = _.debounce(sendQuery, 300); setSearchQuery(prevSearch => { // In case there is a previous search triggered, // cancel() will prevent previous method to be called if (prevSearch.cancel) { prevSearch.cancel(); } return search; }); search(value); }; /** * In charge to send the value * to the API. * @param {*} value */ const sendQuery = async value => { const { cancelPrevQuery, result } = await fetchData(value); if (cancelPrevQuery) return; if (result.Response === 'True') { setDataList(result.Search); setErrorMssg(''); } else { setDataList([]); setErrorMssg(result.Error); } }; return ( <div> <div> <p>Type to search!</p> <input type="text" value={query} placeholder="Enter Movie Title" onChange={onChange} /> </div> <div> <ResultListComponent items={dataList} /> {errorMssg} </div> </div> ); }; export default SearchBarComponent; 

You can refer to this middle article I just did:

https://medium.com/@mikjailsalazar/just-another-searchbar-react-axios-lodash-340efec6933d

-2
source

Source: https://habr.com/ru/post/1261464/


All Articles