lundi 22 juin 2020

React Checkbox Form State is Delayed

I have a form I am mapping a list of checkbox inputs to using React. The mapping function receives a list of JSON objects and maps them to inputs as follows:

const listCustomBenefits = props.customBenefits.map(benefit => {
    return(
        <div className="flex">
            <input onChange={props.handleCustomBenefitsChange} id={benefit.id} key={benefit.id} 
               className="my-auto" type="checkbox" checked={benefit.included}></input>
            <p className="my-auto px-2">{benefit.benefit}</p>
        </div>
        )
})

props.customBenefit is formatted as followed:

const customBenefit = useState([{benefit: "first benefit description",
id: 1,
included: false,
name: "First Benefit"},
{benefit: "second benefit description",
id: 2,
included: false,
name: "Second Benefit"}])

listCustomBenefits is then returned in the component's return JSX. When a checkbox is clicked, handleCustomBenefitsChange updates the state of custom benefits as follows:

const handleCustomBenefitsChange = (event) =>{
    event.preventDefault()
    const newCustomBenefits = customBenefits.map(benefit =>{
        if(benefit.id == event.target.id){
            const newCheck = [event.target.checked][0]
            return({...benefit,  included: newCheck})
        }
        else{
            return benefit
        }
    })

    setCustomBenefits(newCustomBenefits)

 }

The function properly updates the state of customBenefits, but the checkbox display is always one event behind (i.e. you have to click the checkbox twice to see the desired change).

I have tried setting state with props on the local component as well (instead of using props directly) but can't seem to get the component to update on the initial click. Can anyone help me resolve this?




Aucun commentaire:

Enregistrer un commentaire