import React, { useEffect } from 'react' import { useForm, usePage } from '@inertiajs/react' import { toast } from 'react-toastify' export default function FormModal(props) { const { modalState } = props const { props: { permissions } } = usePage() const { data, setData, post, put, processing, errors, reset, clearErrors } = useForm({ name: '', permissions: [] }) const handleOnChange = (event) => { if (event.target.type === 'checkbox') { if (!event.target.checked) { setData('permissions', data.permissions.filter(i => i.name !== event.target.name)) return } const permission = permissions.find(i => i.name === event.target.name) setData('permissions', data.permissions.concat(permission)) return } setData(event.target.name, event.target.type === 'checkbox' ? event.target.checked : event.target.value); } const handleReset = () => { reset() clearErrors() modalState.setData(null) } const handleCancel = () => { handleReset() modalState.toggle() } const handleSubmit = () => { const role = modalState.data if(role !== null) { put(route('roles.update', role), { onSuccess: () => Promise.all([ handleReset(), modalState.toggle(), toast.success('The Data has been changed'), ]), }) return } post(route('roles.store'), { onSuccess: () => Promise.all([ handleReset(), modalState.toggle(), toast.success('The Data has been saved'), ]), }) } const handleCheckAll = (event) => { if(event.target.checked) { setData('permissions', permissions) return } setData('permissions', []) } const isChecked = (permission) => { const checked = data.permissions.find(i => i.name === permission.name) if (checked) { return true } return false } useEffect(() => { const role = modalState.data if (role !== null) { setData({ name: role?.name, permissions: role?.permissions }) } }, [modalState]) return (