Reputation: 25
Hello everyone I am beginner at react. I want to search i my state which array of object I write the following function for the search. It works perfectly fine to search for the first time.
But when I try to search for the second time it does't work because "tempdata" is now in state. Can anyone please help me to sort?
Here are my code please have a look thanks in Advance.
categorySearch(event){
let tempdata=[];
this.state.data.map((categoryObject,index) => {
if(categoryObject.name.includes(event.target.value)){
tempdata.push(categoryObject);
}
this.setState({data:tempdata});
});
}
Upvotes: 2
Views: 79
Reputation: 36179
I think filter
is a better option here instead of map
?
Filter returns a new array with all the items that passed the internal conditional - in your case the String includes
method.
categorySearch(event){
const filteredElements =
this.state.data.filter(categoryObject => categoryObject.name.includes(event.target.value));
this.setState({filteredElements: filteredElements});
}
Additionally, I suggest keeping your original data unmodified and use a new key in your state filteredElements
to store all the search results that match the search query. That way if you want to do a second search, all the original data is still available.
Upvotes: 1