I have the following states:
let [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [checkIn_month, setCheckInMonth] = useState(null);
I have an click event listener
assigned directly to JSX's
element tbody
. Using event delegation
to click on the td elements
.
And in the following function if i click on a day that is in the previous month i need to decrement the currentMonth state
and after that to set the new value of currentMonth
in the setCheckInMonth
state.
The problem is:
When i use the setCheckInMonth(currentMonth)
state hook it gives the old value, not the new one.
let [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
const [checkIn_month, setCheckInMonth] = useState(null);
const selectDate = e => {
if (e.target.tagName === 'TD') {
if (e.target.classList.contains('previous-month-day')) {
setCurrentMonth(currentMonth => currentMonth - 1);
setCheckInMonth(currentMonth);
}
}
}
What if i do something like this:
setCurrentMonth(currentMonth => currentMonth - 1);
setCheckInMonth(currentMonth - 1);
Is this a correct way of doing it ?