Mocha
Mocha

Reputation: 131

now.getTime() inside useEffect doesn't work

I wanted to record how many time passed until user click the button. My plan was like: (the time when user enter the page) - (the time when user click the button) = how many milliseoconds passed!

but my code had an bug and error. my useEffect didn't go what I wanted.. It didn't memorized the time when user entered the page.

console said :

๐Ÿ‘‰undefined

and when first hit:

-1611798597788milliseconds passed

(it worked well as I planned when second hit. weird ๐Ÿค”)

here's my code:

const UserTimer = () => {
  const [startTime, setStartTime] = useState(null);
  const [endTime, setEndTime] = useState(0);
  const [diff, setDiff] = useState(0);

  useEffect(() => {
    let now = new Date();
    setStartTime(now.getTime());
    console.log('๐Ÿ‘‰' + startTime);
  }, []);

  const onClick = () => {
    setEndTime(Date.now());
    setDiff(endTime - startTime);
    setStartTime(endTime);
  };

  return (
    <div>
      <p>{diff}milliseconds passed</p>
      <button onClick={onClick}>click here</button>
    </div>
  );
};

thank you in advance.

Upvotes: 0

Views: 503

Answers (2)

Leonardo Muz&#237;
Leonardo Muz&#237;

Reputation: 65

That's because your startTime state is set as null here:

const [startTime, setStartTime] = useState(null);

So first click it is still null, so your setDiff(endTime - startTime); returns the negative number. You can try to solve it using:

useEffect(() => {
   let now = new Date();
   setStartTime(now.getTime());
   console.log('๐Ÿ‘‰' + startTime);
}, [startTime]);

Upvotes: 0

thul
thul

Reputation: 1186

setState does not happen synchronously, so you will not see it change instantly. Best to set a variable then use that variable for your math.

Maybe something like this?

const UserTimer = () => {
const [startTime, setStartTime] = React.useState(null);
const [diff, setDiff] = React.useState(0);

React.useEffect(() => {
  const now = Date.now()
  setStartTime(Date.now());
  console.log('๐Ÿ‘‰' + now);
}, []);

const onClick = () => {
  const endTime = Date.now()
  setDiff(endTime - startTime);
  setStartTime(endTime);
};

return (
  <div>
    <p>{diff}milliseconds passed</p>
    <button onClick={onClick}>click here</button>
  </div>
);
};

Upvotes: 1

Related Questions