Filter React Native Data

Viewed 2425

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

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 2 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..

Thank you

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 */)
}
Related