React Native Sorting issue

Viewed 265

I am fetching a JSON file and storing it in two arrays and sorting one of them by its rate as it shown below, unfortunately, it sorting the two arrays the recentPro and ratedPro but the desired array to be sorted is ratedPro only

fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          recentPro: responseJson.products,
          ratedPro:responseJson.products,  
        },
         function() {

           //Sort by rate
           const ratedpro= this.state.ratedPro.sort(function(a, b) {
            return Number(b.rate) - Number(a.rate);
        })
        this.setState({
            ratedPro: ratedpro,     
        })  

        })

Flat List

<FlatList
                data={this.state.ratedPro}
                renderItem={this.mostrated}
                keyExtractor={item => item.pro_name}/>


<FlatList
                data={this.state.recentPro}
                renderItem={this.rederItem}
                keyExtractor={item => item.pro_id} />
1 Answers

You are assigning both this.state.recentPro and this.state.ratedPro to reference the same array. You are then mutating that array which will cause the change to be reflected in both this.state.recentPro and this.state.ratedPro, because both of these variables reference that same (now mutated) array.

You could shallow copy the array with slice() to achieve different sorting on the two arrays:

    this.setState({
      recentPro: responseJson.products.slice(),
      ratedPro:responseJson.products.slice(),  
    },

You're also triggering unnecessary and premature renders by calling setState multiple times, consider the following more concise solution which also deos some sanity checks on response to prevent your application from relying on the response of the API you are fetching data from:

fetch(url)
  .then(response => response.json())
  .then(responseJson => {
    const { products } = responseJson

    if (products && Array.isArray(products)) {  
      const recentPro = products.slice()

      const ratedPro = products.slice().sort((a, b) => Number(b.rate) - Number(a.rate))

      this.setState({
        recentPro,
        ratedPro,  
      })
    } else { /* display error to user */ }
  }
Related