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 badges2 Answers
Reset to default 7you 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
})
}
}
本文标签:
版权声明:本文标题:javascript - React Native - How to handle TextInput onChangeText event to wait before execute function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744045161a2581386.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论