In general setState or useState in React is asynchronous. So, the updated state we'll not be able to capture in the as soon as we update the state.
In hooks, the updated state will be available in the next render only. So, in order to see if the state is getting updated or not, we can make use of useEffect hook. Below is the example for the same.
const { useState, useEffect } = React;
const App = () => {
const [students, setStudents] = useState([]);
const onChangeHandler = event => {
const {target: {id, value}} = event;
setStudents(prevStudents => {
//Push the new object with the id as key and value
//of the checkbox as value in the array.
//In your case the value will be the student id.
//But here for simplicity I have used 1, 2 as ids & values
return [...prevStudents, {[id]: value}]
});
}
//To print the initial state as well as whenever the state(i.e., students gets updated
useEffect(() => {
console.log(students);
}, [students])
return (
<div>
<div>
<input type="checkbox" id="1" value="1" onChange={onChangeHandler}/>
<span>Input 1</span>
</div>
<div>
<input type="checkbox" id="2" value="2" onChange={onChangeHandler}/>
<span>Input 2</span>
</div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Note: For the demo purpose I have not considered removing the objects from the state when the checkbox is getting unchecked. I'm just adding a new object with id as key and value as value in the array irrespective of the state of the checkbox. So, please update the onChangeHandler logic as per your needs.
setSelectedStudentsis not synchronous. So, the state changes you can see on the next render. That's why in theconsole.logyou are seeing the previous state.useEffectin order to see the changes.setSelectedStudentsinstudentsChangeHandler. instead you should add the new id. That's the coding mistake I can say.