othman safadi
othman safadi

Reputation: 331

React Native Sorting Issue

I am displaying an array (CatFilterPro) in a Flatlist, when a button is pressed I want to sort it by high price to low and when the other button is pressed do the reverse, the below code is working fine for the first press, but it could not sort it again after the first sort.

lowpricefilter() {

    this.fc= this.state.recentPro2
    this.fc.sort(function(a, b) {
        return Number(a.pro_price) - Number(b.pro_price);
    })
    this.setState({
        CatFilterPro: this.fc,
        modalVisible: false

    })   
}


highpricefilter() {
    this.fc= this.state.recentPro2
    this.fc.sort(function(a, b) {
        return Number(b.pro_price) - Number(a.pro_price);
    })
    this.setState({
        CatFilterPro: this.fc,
        modalVisible: false
    })   
}

Upvotes: 0

Views: 346

Answers (2)

Dan
Dan

Reputation: 8794

sortByDescending = (a, b) => {
  if(a === b) return 0;
  if(a > b) return -1;
  return 1;
};

sortByAscending = (a, b) => a - b;

sort = sortFunction => {
  const { recentPro2: fc } = this.state;
  return fc.sort(sortFunction);
}

lowpricefilter = () => {
  const sortedAscending = this.sort(this.sortByAscending));
  this.setState({
    CatFilterPro: sortedAscending,
    modalVisible: false
  });
}

highpricefilter = () => {
  const sortedDescending = this.sort(this.sortByDescending));
  this.setState({
    CatFilterPro: sortedDescending,
    modalVisible: false
  });
}

Upvotes: 1

Anis D
Anis D

Reputation: 761

You have to bind your functions in your constructor

this.highpricefilter = this.highpricefilter.bind(this);
this.lowpricefilter = this.lowpricefilter.bind(this);

Upvotes: 0

Related Questions