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!
JavaScript
x
33
33
1
type FriendsProps = {
2
friendsList:
3
{
4
"id": number,
5
"firstName": string,
6
"lastName": string,
7
"photoUrl": string,
8
"online": boolean
9
}[]
10
}
11
12
const Friends: React.FC<FriendsProps> = (props) => {
13
const [friends, setFriends] = useState([{}]);
14
15
useEffect(() => {
16
const newFriends = props.friendsList.sort((friendA, friendB) => {
17
return friendA.online === friendB.online ? 0 : friendA.online ? -1 : 1;
18
})
19
setFriends(newFriends)
20
}, []);
21
console.log(friends)
22
23
return (
24
<div className="friends-list">
25
{friends.map((friendInfo, id) => {
26
return (
27
<h1>{friendInfo.firstName}</h1>
28
)
29
})}
30
</div>
31
);
32
};
33
console.log (friends) show at first empty array and then fill
Advertisement
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:
JavaScript
1
23
23
1
const Friends: React.FC<FriendsProps> = props => {
2
const sortedFriends = React.useMemo(
3
() =>
4
props.friendsList.sort((friendA, friendB) => {
5
return friendA.online === friendB.online ? 0 : friendA.online ? -1 : 1;
6
}),
7
[props.friendsList]
8
);
9
10
console.log({sortedFriends});
11
12
return (
13
<div className='friends-list'>
14
{/* now map over your sortedFriends array */}
15
{sortedFriends.map((friendInfo, id) => {
16
// add a key when you're mapping over an array
17
return <h1 key={id}>{friendInfo.firstName}</h1>;
18
})}
19
</div>
20
);
21
};
22
23