Accessing the previous state of a functional component with state being an object

2k views Asked by At

Given that you can access the previous state when changing the current state by passing an arrow function like in the stopwatch function below:

function App() {
   const [time, setTime] = useState(0)

function counter() {
   setTime(prev => prev + 1)
}

return (
<div>
 <p>{time}<p>
 <button onClick={counter}>Click Me<button/>
</div>
)

}

Can I do the same when the state is an object? Is it a syntax issue I am having or it cannot be done? What do I write where I have the question marks?

function App() {
   const [time, setTime] = useState({sec: 0, min: 0, hour: 0})

function stopwatch() {
   setTime(prev??? => ????)
}

return (
<div>
 <p>{time.sec} {time.min} {time.hour}<p>
 <button onClick={stopwatch}>Click Me<button/>
</div>
)

}

```
1

There are 1 answers

0
gabriel_tiso On

I think that you should try to make them separated, since minutes, seconds and hours increase in different moments. If you want to make a change in the minutes, for example, you can apply this logic to the object

function App() {
   const [time, setTime] = useState({sec: 0, min: 0, hour: 0})

function stopwatch() {
  setTime(prevTime => {
  return {
     ...prevTime,
     minutes: prevTimes.minutes + 1 // or you could directly change it..
  }  
})
}

return (
<div>
 <p>{time.sec} {time.min} {time.hour}<p>
 <button onClick={stopwatch}>Click Me<button/>
</div>
)

}

This logic can be applied to every number of changes you want to make, minutes, seconds and hours, just hours, etc.