I'm trying to make a team draw app. I have a button that when you click on them runs a function. This function must be fill the state of 'Players' but when i click this button at first time, this returns an empty array. After second click works normally. I read all similar tickets like this in this page but I can't fix my problem.
//Code
import React, { useState, useEffect } from "react";
import NewPlayerButton from "./NewPlayerButton";
import PlayerList from "./PlayerList";
import NewPlayerForm from "./NewPlayerForm";
const PlayersContainer = () => {
//Estados
const [showAddPlayer, setShowAddPlayer] = useState(false);
const [players, setPlayers] = useState([]);
const [arrayGoalKeepers, setArrayGoalKeepers] = useState([]);
const [arrayPlayers, setArrayPlayers] = useState([]);
//Variables
//Efectos
useEffect(() => {
setShowAddPlayer(showAddPlayer);
}, [showAddPlayer]);
useEffect(() =>{
console.log(arrayGoalKeepers);
}, [])
//Funciones
const showAddPlayerForm = (status) => {
setShowAddPlayer(status);
};
const drawTeams = () =>{
let arrGoalKeepers = players.filter(p =>{
return p.type == "GoalKeeper";
});
let arrPlayers = players.filter(p =>{
return p.type == "Player";
});
setArrayGoalKeepers(arrGoalKeepers);
setArrayPlayers(arrPlayers);
let allPlayers = [...arrayPlayers];
for (let i = allPlayers.length - 1; i > 0; i--) {
let drawedPlayers = Math.floor(Math.random() * (i + 1));
let temp = allPlayers[i];
allPlayers[i] = allPlayers[drawedPlayers];
allPlayers[drawedPlayers] = temp;
}
const halfQuant = Math.floor(allPlayers.length / 2);
console.log(halfQuant);
let team1 = [...allPlayers.slice(0, halfQuant), ...arrayGoalKeepers.slice(0,1)];
let team2 = [...allPlayers.slice(halfQuant), ...arrayGoalKeepers.slice(1)];
console.log(team1);
console.log(team2);
}
return (
<>
<NewPlayerButton showStatus={showAddPlayer} showFn={showAddPlayerForm} />
{showAddPlayer && (<NewPlayerForm players={players} setPlayer={setPlayers} showMenu={setShowAddPlayer}/>)}
<hr />
<PlayerList players={players}/>
<button className="btn btn-success w-100 border text-uppercase" onClick={drawTeams}>
⚽ Sortear
</button>
</>
);
};
export default PlayersContainer;