skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have fixed it by using filter:

    const handleOnChange = (e, i) => {
        const { checked, id } = e.target;
        if (checked) {
            setPurchaseTypes([...purchaseTypes, purchaseData[i]]);
        } else {
            setPurchaseTypes((prev) => prev.filter((item) => {
                return item.id !== parseInt(id)
            }))
        }
    }
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search