1

The value of my timeDifference variable is not getting set in the code below. What am I doing wrong? My theDiff variable does contain a value, but when I run my setTimeDifference call it doesn't not set timeDifference to that value.

const[timeDifference, setTimeDifference] = useState();

const getTimeDifference = (signInTime) => {
    let now = Date().toLocaleString();
    let timeIn = new Date(signInTime);

    now = moment(now);
    timeIn = moment(timeIn);
    let theDiff = moment(now).diff(moment(timeIn), 'minutes');
    setTimeDifference(theDiff);
}

useEffect(() => { 
    getTimeDifference(props.timein);
    console.log(timeDifference);              
}, []);
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 2
    Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – Ajeet Shah Mar 18 '21 at 17:00
  • As you are using hook, check this: https://stackoverflow.com/q/54069253/2873538 – Ajeet Shah Mar 18 '21 at 17:02

1 Answers1

0

Every value referenced inside the effect function should also appear in the dependencies array. Try this:

useEffect(() => { 
    getTimeDifference(props.timein);
    console.log(timeDifference);              
}, [props.timein,setTimeDifference,timeDifference]);
Ivan V.
  • 7,593
  • 2
  • 36
  • 53