my purpose is to allow two days of the week to be a weekend
the problem is with this approach i am unable to limit the weekend array to hold only two days its always going beyond
i think the problem is that the state is async and setState and useEffect are having different values but unable to solve the problem
const weekendDays = [
"Saturday",
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
];
const [weekend, setWeekend] = useState([]);
const handleWeekendSelection = ({ target }) => {
if (target.checked) {
!weekend.includes(target.value) &&
setWeekend((prev) => [...prev, target.value]);
} else {
setWeekend((prev) => [...prev].filter((day) => day !== target.value));
}
};
useEffect(() => {
console.log(weekend.length);
if (weekend.length > 2) {
const checkboxes = document.querySelectorAll(
"input[type=checkbox]:checked"
);
const lastCheckbox = checkboxes[checkboxes.length - 1];
lastCheckbox.checked = false;
setWeekend((prev) => {
const correctedWeekend = prev;
correctedWeekend.length > 2 && correctedWeekend.pop();
return [...correctedWeekend];
});
}
}, [weekend.length]);
<div>
{weekendDays.map((day, index) => {
return (
<div key={index}>
<input
type="checkbox"
value={index}
onChange={handleWeekendSelection}
/>
<label>{day}</label>
</div>
);
})}
</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…