Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter React Native Data

I searched all day but I didn't find the solution to my problem. I'm new to React Native so I'm stuck ...

Here's my problem :

I fetch an API to the get data, I'm doing it with axios and it's ok I can render my component !

Then I don't want to display ALL ITEMS of my Array but I want to display some items according to different values with two buttons :

<Button onPress={Get ALL ITEMS with this value}/>
<Button onPress={Get ALL ITEMS with ANOTHER VALUE} />

My issue is that I'm modifying the state of my array products with new information but that's not what I want. I always want that I'm displaying information according to a particular VALUE in the Array and still get my Full Array...

Here's some piece of code of what I'm doing :

onPressFirstButton() {
let newArray = [...this.state.products];

this.setState({
  products: newArray.filter(function(product){
    return product.value == 32;
  })
});
}
onPressSecondButton() {
let otherArray = [...this.state.products];

this.setState({
  products: otherArray.filter(function(product){
    return product.other_value == 389;
  })
});
}

I'm sure it's not the best way because it's not working.. I hope you will understand what I'm trying to say..

like image 454
Clément CREUSAT Avatar asked Aug 06 '26 09:08

Clément CREUSAT


1 Answers

Since you seem to be using the products property to populate your template, consider using a separate variable for that instead, that way you don’t have to mess with your state when doing your filtering. Maybe this will help:

displayProducts = []

onPressFirstButton () {
  this.displayProducts = this.state.products.filter(product => /* logic */)
}
like image 109
Ben Steward Avatar answered Aug 07 '26 23:08

Ben Steward