3

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 Answer 1

1

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 */ }
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.