Reputation: 125
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>
)
}
```
Upvotes: 1
Views: 2175
Reputation: 1137
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.
Upvotes: 2