Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I increment a useState Object

const [counter, setCounter] = useState({seconds:0, minutes:0})

somehow i have difficulties to update these objects. i would like to call setcounter in an interval and update counter.minutes in an useEffect every 60s. but with each try my code gets more and more spaghetti :D

it is more of a general understanding/syntax problem i have. my main attempt looked like this:

 setCounter((counter)=> counter.seconds +1) 

or

setCounter((counter) => {...counter, second: second+1)

mby this helps displaying how i was trying to achieve the result –

like image 627
mindgrapes Avatar asked Sep 14 '25 09:09

mindgrapes


1 Answers

I think you want take

setCounter( (counter) => ({...counter, second: second+1}));

and make it

setCounter( counter => ({...counter,seconds:counter.seconds+1 } ));
like image 81
PhantomSpooks Avatar answered Sep 17 '25 03:09

PhantomSpooks