0

I've build a Forum on React. On the componnent that the posts are displayed in, I added sort option. when I call to setState({posts: sortedPosts}) the page does'nt rerendering himself. this is the code in react:

<select
          className="form-select p-2 rounded mb-3"
          aria-label="Default select example"
          onChange={ e => {
            let sortedPosts =  postService.sortPostsBy(nonSortedPosts, e.target.value);
            // console.log("non sorted:", nonSortedPosts);
            // console.log("sorted:", sortedPosts);
            this.setState({ posts: sortedPosts});
          }}
        >
          <option defaultValue value="NEWEST">Sort by Newest</option>
          <option value="OLDEST">Sort by Oldest</option>
          <option value="LIKES">Sort by Likes</option>
          <option value="COMMENTS">Sort by Comments</option>
        </select>

the function of sorting works excellent and the all problem is with the setState here is the code of sorting function :

function sortPostsBy(postsArray, sortBy) {
//duplicate the array
let [...posts] = postsArray;

switch (sortBy) {
  case "NEWEST":
    posts.reverse();
    break;
  case "OLDEST":
    break;
  case "LIKES":
    posts.sort((a, b) => {
      return b.numOfLikes - a.numOfLikes;
    });
    break;
  case "COMMENTS":
    posts.sort((a, b) => {
      return b.comments?.length - a.comments?.length;
    });
    break;
  default:
    //newest
    posts.reverse();
    break;
}

return posts;

};

thank you for your help!

  • 1
    Does this answer your question? [Why is useState not triggering re-render?](https://stackoverflow.com/a/56266640/636077) – ray hatfield Nov 01 '21 at 21:04

0 Answers0