How can I render array after sorting in React hooks

Tags: , ,



I get by props array with objects and then I nedd to sort them and render, but now I get array and after sorting it I can’t render sorted array. I use useEffect and there sorting an array and by setState put sorted array into variable but when I try to rended it I have error that array are empty. How can I fix it? Maybe I can somehow change props.friendsList with newFriends? it will be great!

type FriendsProps = {
    friendsList:
    {
        "id": number,
        "firstName": string,
        "lastName": string,
        "photoUrl": string,
        "online": boolean
    }[]
}

const Friends: React.FC<FriendsProps> = (props) => {
    const [friends, setFriends] = useState([{}]);

    useEffect(() => {
        const newFriends = props.friendsList.sort((friendA, friendB) => {
            return friendA.online === friendB.online ? 0 : friendA.online ? -1 : 1;
        })
        setFriends(newFriends)
    }, []);
    console.log(friends)
    
    return (
            <div className="friends-list">
                {friends.map((friendInfo, id) => {
                    return (
                        <h1>{friendInfo.firstName}</h1>
                    )
                })}
            </div>
    );
};

console.log (friends) show at first empty array and then fill

Answer

I think it would be better just to sort friends directly. The useEffect and state are unnecessary. To keep this optimised you should use useMemo, but you need to make sure props.friendsList is not changing on every render:

const Friends: React.FC<FriendsProps> = props => {
  const sortedFriends = React.useMemo(
    () =>
      props.friendsList.sort((friendA, friendB) => {
        return friendA.online === friendB.online ? 0 : friendA.online ? -1 : 1;
      }),
    [props.friendsList]
  );

  console.log({sortedFriends});

  return (
    <div className='friends-list'>
      {/* now map over your sortedFriends array */}
      {sortedFriends.map((friendInfo, id) => {
        // add a key when you're mapping over an array
        return <h1 key={id}>{friendInfo.firstName}</h1>;
      })}
    </div>
  );
};



Source: stackoverflow