Home > Software design >  Table not re -rendering after sorting useState object
Table not re -rendering after sorting useState object

Time:08-03

const [members, setMembers] = useState([]);
  useEffect(() => {
    getMembers();
  }, []);

  const sortByName = () => {
    const sorted = members.sort((a, b) => {
      if (a.name < b.name) {
        return -1;
      }
      if (a.name > b.name) {
        return 1;
      }
      return 0;
    }
    );
    setMembers(sorted)
  }

{members.map((person) => {
return (
<Member key={person.member_id} person={person}/>
)})}

The table is not re-rendered with the sorted data after the sortByName function is called, console logging the member variable gives proper sorted data, but the table still displays the old data

CodePudding user response:

I think sort method doesnt return a new array. So maybe u need to try :

setMembers([...sorted])
  • Related