lundi 30 novembre 2020

update state delay in checkbox, React

I have to objects sizes and newProduct , I need to set the available sizes using a checkboxes, it works fine but :

When I check two boxes, the state updates only in the first box , then when pushing the sizes object to the newProduct object , the state on the newProduct did not update until I check the third box (update only the value of the first box)

Here is my code :

function Products(){

    const [sizes, setSizes] = useState({
        s: false, m: false, l: false, xl: false, xxl: false, xxxl: false
    })
    const [newProduct, setNewProduct] = useState({
        productType : "", name : "", price : "", photo : "", sizes : sizes
    })

    const manageSizes = (e) => {
        
        const { name, checked} = e.target
        
        setSizes({...sizes, [name] : checked}) // late (1)
        
        setNewProduct({...newProduct, sizes : sizes}) // late (2)
        
    }
    return (
          {Object.keys(sizes).map((item, index) => (
                <label key={index} htmlFor={item}>{item}
                        <input 
                        type="checkbox"
                        checked={sizes[item]}
                        name={item} 
                        onChange={manageSizes}
                        />
                </label>        
          ))}
    )
}



Aucun commentaire:

Enregistrer un commentaire