Search code examples
react-nativelodashdebouncing

Debouncing search input onChangeText()


Using lodash's debounce(), I'm trying to wait 1.2 seconds before setting a search term in my app's state. But it doesn't seem to run my function when I use it:

onChangeText(text) {
    console.log('setting');
    setSearching(true);
    setSearchTerm(text);
}
render(){
    return(
        <TextInput style={s.input}
            onChangeText={() => {
                _.debounce(this.onChangeText, 1200);
                /*
                doing just...
                this.onChangeText(text)
                ...works
                */
            }}
        />
    )
}

I do not get setting in my console log when using debounce. Any ideas?


Solution

  • Right now you're creating a new instance of debounce on every call of the handler.

    Ideally, you should wrap your entire handler in debounce since debounce creates a debounced function that delays invoking func

    onChangeText={_.debounce(this.onChangeText, 1200)}