Hasan
Hasan

Reputation: 53

State is not updating in React after sorting?

I am trying to sort JSON object by date and number. Everything is working fine when i console log but the state is not getting updated on the GUI side. What am i missing? I am using the functional components. Here is the code...

const Posts = () => {
  const [dummyData, setDummyData] = useState(Data);
  const sortList = (e) => {
    if (e.target.value === "date") {
      handleSort();
    } else if (e.target.value === "upvotes") {
      byUpvotes();
    }
  };
  const handleSort = () => {
    const sortedData = dummyData.sort((a, b) => {
      const c = new Date(a.published);
      const d = new Date(b.published);
      if (c.getDate() > d.getDate()) {
        return c;
      } else {
        return d;
      }
    });
    setDummyData(sortedData);
    console.log(sortedData);
  };

  const byUpvotes = () => {
    const sortByName = dummyData.sort((a, b) => {
      return b.upvotes - a.upvotes;
    });
    setDummyData(sortByName);
    console.log(sortByName);
  };
  return (
    <div>
      {dummyData.map((post) => (
        <PostsItem key={post.id} post={post} />
      ))}

      <div className="row">
        <div className="col-s6">
          <label>Browser Select</label>
          <select className="browser-default" onChange={sortList}>
            <option disabled selected>
              Choose your option
            </option>
            <option value="date">Date</option>
            <option value="upvotes">Upvotes</option>
          </select>
        </div>
      </div>
    </div>
  );
};

Upvotes: 1

Views: 2340

Answers (2)

Gautam shekhar
Gautam shekhar

Reputation: 11

The state will only update when its reference is changed, here in your code state is sorted because the sort function only mutates the original array instead of creating a new array like a map, or filter that gives a new reference. so, you should do like this

 const byUpvotes = () => {
        const sortByName = dummyData.sort((a, b) => {
          return b.upvotes - a.upvotes;
        }).map((num)=>num);
setDummyData(sortByName)};

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 84902

The sort function does not create a new array, it mutates the old one. So you're rearranging the existing state, and then setting state with the same array. Since it's the same array, react thinks the state hasn't changed and skips rendering.

Instead, you will need to make a copy of the array and then sort that. For example:

const byUpvotes = () => {
  const sortByName = [...dummyData];
  sortByName.sort((a, b) => {
    return b.upvotes - a.upvotes
  })
  setDummyData(sortByName)
}

Upvotes: 10

Related Questions