Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Using lodash debounce

I'm playing around with React Native and lodash's debounce.

Using the following code only make it work like a delay and not a debounce.

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

I want the console to log debounce only once if I enter an input like "foo". Right now it logs "debounce" 3 times.

like image 982
Norfeldt Avatar asked Dec 18 '16 17:12

Norfeldt


People also ask

How do you use Lodash debounce in react native?

To use Lodash debounce in a React Native app, we can call debounce with the function we want to debounce. to assign onChangeText to a function that debounce returns which delays setText by 500 milliseconds. And then we set that as the value of the TextInput onChangeText prop.

How do you debounce from Lodash?

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.

How do you use Lodash in react native?

To start using Lodash in React, you need to:Install Lodash by running npm install lodash. Import Lodash to your project by writing import _ from lodash.


1 Answers

Debounce function should be defined somewhere outside of render method since it has to refer to the same instance of the function every time you call it as oppose to creating a new instance like it's happening now when you put it in the onChangeText handler function.

The most common place to define a debounce function is right on the component's object. Here's 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} />   } } 
like image 175
George Borunov Avatar answered Sep 20 '22 06:09

George Borunov