Skip to content
Advertisement

Why is getServerSideProps data being changed?

I’ll fetch data from an API, When I pass my getServerSideProps data to index.js, the prop array is in order by rank. [1,2,3..etc].

ex: data

[
 {rank: 1, price: 123},
 {rank: 2, price: 1958},
 {rank:3, price: 56}
]

When I alter that data into a different variable, for example:

const topPrice = data
    .sort((a, b) => a.price < b.price ? 1 : -1).slice(0, 3);

console log shows data is now sorted by price too, when I only wanted topPrice to be sorted, why?

Advertisement

Answer

sort function alters your original list data. To avoid that case, you should create a copy of your list before calling sort

const data = [{
    rank: 1,
    price: 123
  },
  {
    rank: 2,
    price: 1958
  },
  {
    rank: 3,
    price: 56
  }
]

const topPrice = [...data]
  .sort((a, b) => a.price < b.price ? 1 : -1).slice(0, 3);

console.log({
  data,
  topPrice
})

If you want it clearer, you can introduce a new variable to keep the new array

const data = [{
    rank: 1,
    price: 123
  },
  {
    rank: 2,
    price: 1958
  },
  {
    rank: 3,
    price: 56
  }
]

const copiedData = [...data]
const topPrice = copiedData
  .sort((a, b) => a.price < b.price ? 1 : -1).slice(0, 3);

console.log({
  data,
  topPrice
})
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement