This is part of a previous post: What's the React best practice for getting data that will be used for page render?
I'm adding objects to an array with useState([]). Each object has a firstName and a lastName value. I want to add up all of the length of all the first and last names to get a total character count so that I can then get the average name length for each.
What I have currently is giving me the wrong values: firstName (100) lastName (106)
The values should be 6 & 7
const [players, setPlayers] = useState([]);
const [firstNameCount, setFirstNameCount] = useState(0);
const [lastNameCount, setLastNameCount] = useState(0);
useEffect(() => {
setPlayers([]);
teams.forEach(teamId => {
axios.defaults.headers.common['Authorization'] = authKey;
axios.get(endPoints.roster + teamId)
.then((response) => {
let teamPlayers = response.data.teamPlayers;
console.log(response.data.teamPlayers)
setPlayers(prevPlayers => [...prevPlayers, ...teamPlayers]);
})
.catch((error) => {
console.log(error);
})
});
}, [teams]);
useEffect(() => {
players.forEach(player => {
setFirstNameCount(prevCount => prevCount + player.firstName.length);
setLastNameCount(prevCount => prevCount + player.lastName.length);
})
}, [players]);
If I change the code to this
useEffect(() => {
setPlayers([]);
teams.forEach(teamId => {
axios.defaults.headers.common['Authorization'] = authKey;
axios.get(endPoints.roster + teamId)
.then((response) => {
let teamPlayers = response.data.teamPlayers;
console.log(response.data.teamPlayers)
setPlayers(prevPlayers => [...prevPlayers, ...teamPlayers]);
teamPlayers.forEach(player => {
setFirstNameCount(prevCount => prevCount + player.firstName.length);
setLastNameCount(prevCount => prevCount + player.lastName.length);
})
})
.catch((error) => {
console.log(error);
})
});
}, [teams]);
It slows down the render considerably and I get: firstName (7), lastName (7), which is still wrong.