I'm learning react native and I'm doing a small app that regists the time of sleep for each day.
I'm using the useEffect() to trigger some modifications of values showed on screen, one of those is the average time average()
that I update inside that useEffect:
const [updateAction, setUpdateAction] = useState(false);
useEffect(() => {
console.log("lenght:" + registSleep.length);
var registed = false;
if (!isNaN(enteredHours)) {
for (var i = 0; i < registSleep.length; i++) {
if (
registSleep[i].day === selectedDay &&
registSleep[i].month === selectedMonth &&
registSleep[i].year === selectedYear
) {
registed = true;
registSleep[i].hours = enteredHours;
}
}
if (!registed) {
var newReg = {
day: selectedDay,
month: selectedMonth,
year: selectedYear,
hours: enteredHours,
};
setNewRegist((prevReg) => [
...prevReg,
newReg,
]);
}
if (registSleep.length != 0) {
average();
}
}
console.log("2. lenght:" + registSleep.length);
setviewInfoAction(!viewInfoAction);
}, [updateAction]);
To debug, as you can see I print to console the lenght before I add a new value to the array of regists setNewRegist(...)
and as far as I know it should be printing lenght: 0
and then 2. lenght: 1
but instead it prints lenght: 0
and then 2. lenght: 0
and on the next trigger lenght: 1
and then 2. lenght: 1
.
Why the array is not updating on addition?