Reputation: 3239
What's wrong with my code below? basically I don't want to update my state when user enter extra space at the beginning or at the end.
handleSearchQuery = (e) = {
if(e.target.value.trim() != "") {
this.setState({
q: e.target.value
});
}
}
Upvotes: 1
Views: 1225
Reputation: 59501
The first error seems to be that you forgot a >
in your arrow function. Change the first line to:
handleSearchQuery = (e) => {
Anyway, this is how I would write the whole function:
handleSearchQuery = (e) => {
let str = e.target.value.trim();
if(str != this.state.q) {
this.setState({
q: str
});
}
}
This compares the trimmed input to the existing state of q
. If they are equal, nothing happens. Otherwise, update the state.
I store the trimmed result of the string in a variable as I would otherwise need to trim()
twice... for whatever that's worth.
Upvotes: 2
Reputation: 1926
handleSearchQuery = (e) => {
if(e.target.value.trim() != this.state.q) {
this.setState({
q: e.target.value
});
}
}
Upvotes: 0