I have this component:
"use client";
import { Player } from "@prisma/client"
import { io } from "socket.io-client";
import { useState } from "react";
export default function Leaderboard({ initialPlayers }: { initialPlayers: Player[] }) {
const [players, setPlayers] = useState(initialPlayers);
var socket: any;
socket = io("http://localhost:3001");
console.log(`players (state): `, players)
return (
<div className="w-full h-1/2 bg-red-500">
{players
.sort((a, b) => b.points - a.points)
.map((player) => {
return (
<div key={player.id}>
{player.username} ({player.points})
</div>
);
})}
</div>
);
}
I would expect the following things to happen when the component is used:
- props
initialPlayersis passed into the component from its parent playersin state gets initialized withinitialPlayersarray from props- code renders a list of
players
However, the state players is undefined at the time of rendering. The error message I get it:
TypeError: Cannot read properties of undefined (reading 'sort')