I have some checkboxes, all the options checked are sent to the server as an Array, the problem is that unchecking isn't working so after you check one even if you uncheck it is sent to the server, and if you check and uncheck multiple times the same value will be sent many times, here is the code.
const [time, setTime] = useState([]);
function handleChangeTime(e) {
if (e.currentTarget.checked) {
setTime([...time, e.target.value]);
} else {
const newArray = setTime.filter((item) => item !== e.target.value);
setTime(newArray);
}
}
console.log(time)
<h4>Select the best time:</h4>
<form>
<label>
<input
type="checkbox"
name="time"
onChange={handleChangeTime}
value="9:00" />
9:00 a.m
</label>
<label>
<input
type="checkbox"
name="time"
onChange={handleChangeTime}
value="9:30" />
9:30 a.m
</label>
<label>
<input
type="checkbox"
name="time"
onChange={handleChangeTime}
value="10:00" />
10:00 a.m
</label>
</form>
Thank you all in advance for the help!
CodePudding user response:
In order to update state based on its previous value, use the functional update form...
If the new state is computed using the previous state, you can pass a function to
setState
. The function will receive the previous value, and return an updated value.
function handleChangeTime({ target: { checked, value } }) {
if (checked) {
setTime((prev) => [...prev, value]);
} else {
setTime((prev) => prev.filter((item) => item !== value));
}
}