79589542

Date: 2025-04-23 21:52:22
Score: 0.5
Natty:
Report link

Your main problem is the sort function here. See, sort is an in-place operation, and object types in javascript are stored as references. So in your code you:

  1. Use useState to create newArticles (newArticles is a reference)
  2. set a new const sorted as newArticles.sort(...), this is the same reference that points at newArticles since sort is in-place.
  3. Use setNewArticles on sorted which is just the same reference with newArticles. React sees the same value and does not see a reason to re-render.

One option to fix this is to copy the object first send set newArticles to this newly created object like this:

function sortVotes() {
  const sorted = [...newArticles].sort((a, b) => a.upvotes - b.upvotes);
  setNewArticles(sorted);
}

Important note: trying to mutate state variables directly is a bad practice and can cause bugs. Please avoid that.

Reasons:
  • Blacklisted phrase (0.5): upvote
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: ErenYLCN