2

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?

3 Answers 3

3

It might be that the second code snippet doesn't call calculateFinalTime, it just tries to use finalTime.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup. This was it. The other answer may have played a role too (not sure), but the problem was I thought the function would automatically be executed when the component renders
2

I guess that's because of using duplicated variable's name for "finalTime".

think if you change just one variable name, it will work well.

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 finalTime1 = `${stringHrs}:${stringMins}`;
    setFinalTime(finalTime1);
  };

  console.log(finalTime);

1 Comment

This may have played a role, I think the other issue was I wasn't actually calling the function like the other answer suggested. Thanks for your help Youngsoo
1

Even if you have multiple variables with the same name, the scoped variable should take precedence. otherwise you would have at least a syntax error in the console of already declared variable. Either way the code below is a replicate of your code and it works just fine.

function MyComponentClass () {
  const { useState, useEffect } = React

  const [testTime, setTestTime] = useState(0);
  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);
  };
  
  
  useEffect(() => {
    calculateFinalTime([{resultM: Number(testTime)}]);
  }, [testTime]);
  
  
  return <div>
  <input type="number" step="1" value={testTime} onChange={(event) => setTestTime(event.target.value)} />
  <h1>Hello world {finalTime} </h1>
  </div>;
}

ReactDOM.render(<MyComponentClass />, document.querySelector("#app"))
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.