I am working on a React JS with Inertia JS combined application. I'm in the progress to finish my edit feature. so I need to make some checkboxes to be checked default based on a set of values in an array.
I loop the checkbox to let the user choose the list of permissions and some of them should be already checked based on the data from the array.
I'm confused to fix the problem, sometimes I success to checked them but all of the checkbox checked also can't uncheck the checkbox.
this is my code
export default function EditPermission (props){
const {role} = usePage().props
const { data, setData, put, processing, errors, reset } = useForm({
name: role.name || '',
permissions: [] // store the permissions data on role
})
const mapPermissionsOnRole = () => {
for(let i=0; i < role.permissions.length; i++){
data.permissions.push(role.permissions[i]['name'])
}
} //map the already exist permissions and push to data.permissions
const handleChecked = (e) => {
let value = e.target.name;
if (e.target.checked) {
setData("permissions", [...data.permissions, value]);
} else {
setData(
"permissionss",
data.permissions.filter((item) => {
return item !== value
})
);
}
};
const submit = (e) => {
e.preventDefault();
put(route('role.update',permission.id));
};
return (
<AuthenticatedLayout auth={props.auth} errors={props.errors}>
<div className="w-full lg:max-w-6xl mt-6 px-6 py-4 bg-white shadow-md overflow-hidden sm:rounded-lg">
<form onSubmit={submit}>
<div>
{props.permissions && props.permissions.length > 0 ? role.permissions.map((permissions, i) => {
return(
<div>
<Checkbox checked={props.permissions[i].name.includes(data.permissions)} name={permissions.name} value={data.permissions} handleChange={handleChecked} />{permissions.name}
</div>
)
}):<p>Permissions Coming Soon!</p>
}
<PrimaryButton className="ml-4" processing={processing}>
Update
</PrimaryButton>
</div>
</form>
</div>
</AuthenticatedLayout>
)
}
checked={props.permissions[i].name.includes(data.permissions)}|| two things for above code: 1- isdata.permissionsan array?, if so then isprops.permissions[i].namealso an array? 2- we are using data frompropsto update thecheckedprop (shouldn't we usedatafromuseFormhere)?