Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - How to handle TextInput onChangeText event to wait before execute function?

Tags:

I have a search function using Text Input in React native, but the search need to call an API, so I want to hold the onChangeText to run when user finish typing for 2 second,

I've tried to use setInterval nor setTimeout but none of these works,

here's the code I've tried:

<TextInput
  placeholder="search"
  onChangeText={(text) => {
    setTimeout(() => {
      console.log(text)
      console.log("Kepanggil TimeOUTNYAA")
      params.onSearchText(text)
    }, 2000);
  }
}

//function onSearchText

onSearchText(searchText){
  this.setState({text:searchText},()=>{
    this._loadMore() // here's a function to call the API
  })
}

Actual Behavior:

when I'm type am in TextInput the log showing me:

Actual

Expected Behavior:

I want the log showing me only am not a and am

it is possible to do that?

like image 481
flix Avatar asked Jul 02 '18 07:07

flix


1 Answers

you should clear old timeout before set the new one

<TextInput
    placeholder="search"
    onChangeText={(text) => {
        if(this.searchWaiting)
            clearTimeout(this.searchWaiting);
        this.searchWaiting = setTimeout(() => {
            this.searchWaiting = null;
            console.log(text);
            console.log("Kepanggil TimeOUTNYAA")
            params.onSearchText(text)
        }, 2000);
    }}
/>
like image 53
Sadegh Teimori Avatar answered Oct 07 '22 01:10

Sadegh Teimori