I’m creating a football lineup creator where the user can select between a keeper, defender, 3 different types of midfielders, and a forward, with each position having a maximum number (this seems to be working well). However, I want the user not to be able to add more players to the lineup when they’ve added 11 players.
My code as of now is:
const [error, setError] = useState(null);
const [homeTeam, setHomeTeam] = useState(
localStorage.getItem("homeTeam") === null
? {
squad: {
gk: null,
df: [],
cdm: [],
cm: [],
cam: [],
fw: []
},
style: {
color: `#${state.homeTeamColor}`,
numberColor: `#${state.homeTeamNumberColor}`,
nameColor: `#${state.nameColor}`
}
}
: JSON.parse(localStorage.getItem("homeTeam"))
);
const addPlayer = () => {
//const i = 0;
//while (homeTeam.squad.length < 11 && i < homeTeam.squad.length) {
setError(null);
if (playerName === "") {
setError("Player Name required!");
}
//if (homeTeam.squad.length === 11) {
// setError("squad is full!");
//}
else {
let playerObj = {
id: nanoid(),
number: number,
name: playerName,
color:
playerTeam === "homeTeam"
? `#${state.homeTeamColor}`
: `#${state.awayTeamColor}`,
numberColor:
playerTeam === "homeTeam"
? `#${state.homeTeamNumberColor}`
: `#${state.awayTeamNumberColor}`,
namecolor: `#${state.nameColor}`
};
if (playerTeam === "homeTeam") {
if (playerPosition === "gk") {
if (homeTeam.squad.gk !== null) {
setError("goal keeper is full!");
} else {
playerObj.onClick = () =>
playerRemove("homeTeam", "gk", playerObj.id);
setHomeTeam((homeTeam) => ({
...homeTeam,
squad: { ...homeTeam.squad, gk: playerObj }
}));
}
} else if (playerPosition === "df") {
if (homeTeam.squad.df.length === 5) {
setError("defence is full!");
} else {
playerObj.onClick = () =>
playerRemove("homeTeam", "df", playerObj.id);
setHomeTeam((homeTeam) => ({
...homeTeam,
squad: {
...homeTeam.squad,
df: [...homeTeam.squad.df, playerObj]
}
}));
}
}
//CODE IS REPEATED BUT FOR DIFFERENT POSITIONS WHICH I DIDN'T ADD
}
}
//}
setNumber(number + 1);
};
The commented code is what I attempted to do. I tried to wrap the whole code in a while loop and that prevented me from adding any players, and when I implemented an if loop with the condition of if (homeTeam.squad.length === 11) {
setError(“squad if ull”)
}
this adds players without any name being inputted.