mercredi 28 octobre 2020

Handle nested object useState with multiple checkboxes React hooks

I've got useState object like this

export const dataService = () => {
const [data,setData] = useState([
{
dataName:'name1',
dataVisible:false,
dataUrl:'http://localhost:8080/get_document/41gfdg-rewr-432fdsg'
},
{
dataName:'name2',
dataVisible:false,
dataUrl:'http://localhost:8080/get_document/gfd6765-hf34-hgf34'
},
{
dataName:'name3',
dataVisible:false,
dataUrl:'http://localhost:8080/get_document/hgfhbv-dsad-jy675j'
},
{
dataName:'name4',
dataVisible:false,
dataUrl:'http://localhost:8080/get_document/lokg12-jg9d-hgf'
}])

 const handleChange = (e) => {
        setData(prevState => ({
            ...prevState,
              [e.target.name]: e.target.checked
        }))
    }

return(
<div>
 {data.map((item,index) => {
                            return(
                                <Grid>
                                    <Checkbox
                                        name={item.dataName}
                                        onChange={handleChange}
                                        checked={item.dataVisible}
                                        />
                                    <label>{item}</label>
                                </Grid>
                            )
                        })}
<div>
)

}

I want to update dataVisible in time when I click on specify checkbox. But when I click then this data struct don't update this field but add new field with this target checked. Have any idea to solve this problem. I cant invent direction to this fields...




Aucun commentaire:

Enregistrer un commentaire