admin管理员组

文章数量:1356032

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:

Expected Behavior:

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

it is possible to do that?

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:

Expected Behavior:

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

it is possible to do that?

Share Improve this question asked Jul 2, 2018 at 7:40 flixflix 1,9845 gold badges37 silver badges74 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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);
    }}
/>

you simply can not put setTimeOut or any kind of code on onChangeText.Its call back function that means after the event fire u received some text that is useless in your scenario(bcz event is fired and API is called in onSearchText ).

what u can do is in your onSearchText function you can conditionally returns text like if the text length is greater then 2 or 3 then only call the API.Like this:

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

本文标签: