I’m making an attendance form where teachers can mark who’s absent and not and check who was absent the previous days. I have the current date at the top and button which allows it to change the date forward and back. However, when I try to increase the value it works fine, but then when I decrease it increases by one first and then decreases after every click.
const [date, setDate] = useState()
var today = new Date();
var dd = parseInt(String(today.getDate()).padStart(2, '0'));
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
useEffect(() => {
setDate(today)
}, [])
const[newDay, setNewDay] = useState(dd)
const changeToTomorrow = () => {
setNewDay(newDay + 1)
setDate(newDay + '/' + mm + '/' + yyyy)
console.log(date)
}
const changeToYesterday = () => {
setNewDay(newDay - 1)
setDate(newDay + '/' + mm + '/' + yyyy)
}
return (
<div className="attendance-today-container">
<h1>Daily attendance</h1>
<div className='change-date-container'>
<div className='change-date'>
<i class="fas fa-arrow-left" onClick={changeToYesterday}></i>
<p>{date}</p>
<i class="fas fa-arrow-right" onClick={changeToTomorrow}></i>
</div>
</div>
>Solution :
You are trying to set two states in a row while those are asynchronous and might not give you the updated value of newDay by the time you set date.
A fast fix can be as follows (I rearrange the code a bit with spacing):
import {useState, useEffect} from "react";
export default function SomeComponent() {
const [date, setDate] = useState()
var today = new Date();
var dd = parseInt(String(today.getDate()).padStart(2, '0'));
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
useEffect(() => {
setDate(today)
}, [])
const[newDay, setNewDay] = useState(dd)
const changeToTomorrow = () => {
const updateDay = newDay + 1
setNewDay(updateDay)
setDate(updateDay + '/' + mm + '/' + yyyy)
console.log(date)
}
const changeToYesterday = () => {
const updateDay = newDay - 1
setNewDay(updateDay)
setDate(updateDay + '/' + mm + '/' + yyyy)
}
return (
<div className="attendance-today-container">
<h1>Daily attendance</h1>
<div className='change-date-container'>
<div className='change-date'>
<i class="fas fa-arrow-left" onClick={changeToYesterday}></i>
<p>{date}</p>
<i class="fas fa-arrow-right" onClick={changeToTomorrow}></i>
</div>
</div>
</div>
);
}
Calculate the updated date first in a new variable and then set it to both states:
const changeToTomorrow = () => {
const updateDay = newDay + 1
setNewDay(updateDay)
setDate(updateDay + '/' + mm + '/' + yyyy)
console.log(date)
}
const changeToYesterday = () => {
const updateDay = newDay - 1
setNewDay(updateDay)
setDate(updateDay + '/' + mm + '/' + yyyy)
}