Itizaz Adil
Itizaz Adil

Reputation: 25

How to search again in data state after set state function

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

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

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

Related Questions