I have a react functional component for a timesheet app where users select times and the app tells them the total time they worked that week. In my component I have a function which takes a series of values and adds them up together to get a weekly total of hours worked.
I'm getting a strange result where if I organize the code one way, it works, but
this works:
const calculateFinalTime = (times) => {
const totalMinutes = times.reduce((acc, cur) => {
return typeof cur.resultM === "number" ? (acc += cur.resultM) : acc;
}, 0);
const finalHrs = Math.floor(totalMinutes / 60);
const finalMins = totalMinutes % 60;
const stringHrs = String("0" + finalHrs).slice(-2);
const stringMins = String("0" + finalMins).slice(-2);
const finalTime = `${stringHrs}:${stringMins}`;
return finalTime;
};
console.log(calculateFinalTime(times));
By works I mean I get a value for the sum in the console
But this doesn't:
const [finalTime, setFinalTime] = useState("");
const calculateFinalTime = (times) => {
const totalMinutes = times.reduce((acc, cur) => {
return typeof cur.resultM === "number" ? (acc += cur.resultM) : acc;
}, 0);
const finalHrs = Math.floor(totalMinutes / 60);
const finalMins = totalMinutes % 60;
const stringHrs = String("0" + finalHrs).slice(-2);
const stringMins = String("0" + finalMins).slice(-2);
const finalTime = `${stringHrs}:${stringMins}`;
setFinalTime(finalTime);
};
console.log(finalTime);
For some reason, no value is showing up in my console. Nor does it work if I try to display the value in a div.
Anybody can clue me in on why?