skip to Main Content

I want to update the days value inside the state object each time and increate it’s value by one

const [leap, setLeap] = useState({state: false, days:0})

So i tried doing it like that but that did not help

setLeap((prevState)=> ({...prevState, days: days++ }))}

2

Answers


  1. Destructure days out of the previous state, and assign days + 1 to the new days state:

    setLeap(({ ...prevState, days }) => ({ ...prevState, days: days + 1 }))}
    
    Login or Signup to reply.
  2. You need to use the days key from the prevState for incrementing. Do as follows:

    setLeap((prevState)=> ({...prevState, days: prevState.days + 1 }))}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search