I am running into an issue with React where my hook state is updating without my calling setState.
const [dataSet2, setDataSet2] = React.useState([
[2, 3, 4],
[5, 6, 7],
[8, 9, 9],
]);
const badFunction = () => {
let selections = [];
let newSelections = [];
let winPercent = 0;
let newWinPercent = 1;
const depth = 2;
const dataHolderTest = dataSet2;
let firstWeekTest = dataHolderTest[0];
const weekOneTeamsTest = firstWeekTest.slice(0, depth);
for (const weekOneTeamTest of weekOneTeamsTest) {
let secondWeekTest = dataHolderTest[1];
newWinPercent = weekOneTeamTest.win_percent * newWinPercent;
newSelections.push(weekOneTeamTest.team);
for (const team2 of secondWeekTest) {
removeAllSelectedTeams(newSelections, secondWeekTest, team2);
}
}
console.log(dataSet2);
};
const removeAllSelectedTeams = (selections, dataHolder, team) => {
if (selections.includes(team.team)) {
const currentTeam = dataHolder.indexOf(team);
dataHolder.splice(currentTeam, 1);
}
return dataHolder;
};
I've been picking through this for a while now and it seems like the removeAllSelectedTeams
function is the problem.
Still I don't understand how my dataSet2
is being altered without calling the hook setDataSet2
CodePudding user response:
If you want to make a copy of an array or an object, you need to do it like this.
listTwo = [...listOne]
or ObjectTwo = {...ObjectOne}
. Simply using =
and not using the spread operator does not make a copy of that array or object for you, rather gives you another reference to the same array or object.
CodePudding user response:
Try copying the array to dataHolderTest
instead of assigning it equal to dataSet2
with the spread operator ...
This way your not changing the original dataSet2
variable when interacting with dataHolderTest
const dataHolderTest = [...dataSet2]