Skip to content
Advertisement

push() removing previous values

I’m trying to push new values to an array but all I’m getting is only the last value computed. I’ve looked at other answers but couldn’t seem to figure it out. I appreciate the help thanks.

brief: upon clicking start I set a new date, then upon each time I click on the square div, the time is calculated between the previous date and the current date and the difference (diff) is oputput. I am attempting to save all the diff values into an array called diffArray using push() but only the last value is being saved/ output.

JavaScript

Advertisement

Answer

JavaScript

This won’t work because your hook will have the value after the end of the function. You need to do:

JavaScript

Then, your array has only the latest value because you need to convert it to a useState hook: const [diffArray, setDiffArray] = useState([]) .

When you’ve done it, refacto your function to:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement