Making a small todo app, I want to add the functionality that when the task is checked, the checked task goes into an array. On first click the task consoles an empty array, then when unchecked and checked again, my array gets updated. Any reason as to why it takes two click for array to update?
function SelectTodo({ todo }) {
const [checkboxChecked, setCheckboxChecked] = React.useState([]);
const handleInputChange = (e) => {
const checked = e.target.checked;
let value = e.target.value;
if (checked) {
setCheckboxChecked((prevChecked) => [...prevChecked, value]);
console.log("checkBoxArrray:" + checkboxChecked);
} else {
console.log("unchecked");
}
};
return (
<label className="todo-list__label">
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="checkbox"
name="task"
id="inlineCheckboxh1"
value={todo}
onChange={handleInputChange}
/>
<label className="form-check-label" htmlFor="inlineCheckboxh1">
{todo}
</label>
</div>
</label>
);
}
ReactDOM.render(<SelectTodo todo={5} />, document.getElementById("root"));
<div id="root" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>