I have data like this:
const [purchaseTypes, setPurchaseTypes] = useState([]);
const purchaseInitData = [
{ id: 1, name: 'liveType', purchaseType: 'liveType', label: 'purchase live training' },
{ id: 2, name: 'courseType', purchaseType: 'courseType', label: 'purchase course videos'}];
input checkboxes:
{purchaseData.map((item, index) => {
return (
<div className="flex items-center mb-2" key={index}>
<input type="checkbox" id={item.id} name={item.name} onChange={(e) => handleOnChange(e, index)} />
<label htmlFor={`custom-checkbox-${index}`} style={{ marginLeft: '15px' }}>{item.label}</label>
</div>
)
})}
const handleOnChange = (e, i) => {
const newData = [...purchaseData];
const { checked } = e.target;
if (checked) {
setPurchaseTypes((prev) => [...prev, newData[i]]);
} else {
setPurchaseTypes(newData.splice(i, 1));
}
}
I am able to set data to state but unable to remove the last one when I uncheck
2
Answers
I have fixed it by using filter:
The code snippet you have provided is not very clear. Do you also have purchaseTypes state in your code? And what are you trying to display, purchaseData? But. it is not initialised or set in the code. It would be helpful if you could post your whole code.