I am currently working on developing a mobile app that allows users to create teams and players and save them into a database. While I have successfully implemented the team creation functionality, I am facing challenges with the deletion of individual players. I can delete an entire team, but I am unable to remove a single player. Below is a snapshot of my database for reference.
Here is the code snippet for creating a team in the database:
const createTeam = async () => {
const userTeamRef = ref(database, 'users/' + userId + '/teams');
const newTeamRef = push(userTeamRef);
const newTeamKey = newTeamRef.key;
const teamID = newTeamKey;
const teamRef = ref(database, 'teams/' + teamID);
const newTeam = {
teamID: teamID,
name: teamName,
players: players.map(player => ({
playerID: player.playerID,
name: player.name,
stats: playerStats[player.playerID] || {
plus: false,
minus: false,
shot: false,
shotOnGoal: false
}
})),
};
try {
await set(teamRef, newTeam);
console.log('New team created successfully!');
} catch (error) {
console.error('Error creating new team:', error);
}
};
const addPlayer = () => {
const playerID = push(ref(database, 'players')).key;
setPlayers([...players, { name: playerName, playerID }]);
setPlayerStats(prevState => ({
...prevState,
[playerID]: {
name: playerName,
plus: false,
minus: false,
shot: false,
shotOnGoal: false
}
}));
setPlayerName('');
};
Here are the deletion methods from another component:
useEffect(() => {
const teamsRef = ref(database, 'teams');
onValue(teamsRef, (snapshot) => {
const data = snapshot.val();
if (data) {
const teamsArray = Object.values(data);
setTeams(teamsArray);
}
});
return () => {
};
}, []);
useEffect(() => {
if (selectedTeam) {
setPlayers(selectedTeam.players);
} else {
setPlayers([]);
}
}, [selectedTeam]);
const handleDeletePlayer = (playerID) => {
console.log("Deleting player", playerID);
if (selectedTeam) {
const teamRef = ref(database, `teams/${selectedTeam.teamID}/players/${playerID}`);
console.log(teamRef);
remove(teamRef)
.then(() => {
console.log(playerID, 'successfully removed');
setPlayers(prevPlayers => prevPlayers.filter(player => player.playerID != playerID));
console.log(players);
})
.catch((error) => {
console.error('Error removing player:', error);
});
}
};
const handleDeleteTeam = () => {
if (selectedTeam) {
const teamRef = ref(database, `teams/${selectedTeam.teamID}`);
remove(teamRef)
.then(() => {
console.log(selectedTeam.teamID, 'successfully removed');
setPlayers([]);
setSelectedTeam(null);
})
.catch((error) => {
console.error('Error removing team:', error);
});
}
};
And here is the sample data from the database:
{
"-NvajG9MkZFjZXgrAn-E": {
"name": "Canada",
"players": [
{
"0": {
"name": "Sidney Crosby",
"playerID": "-NvajBsvVwe7bJ6kbXXh",
"stats": {}
}
},
{
"1": {
"name": "Connor McDavid",
"playerID": "-NvajFnxRRfc74Vg7Ysu",
"stats": {}
}
}
],
"teamID": "-NvajG9MkZFjZXgrAn-E"
}
}