checkbox not working - Inertia with React
I have a form in a modal that creates a user with roles. When I try to check the roles and output the data in the console, I get the error: Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the component's lifetime.
const {roles, users} = usePage().props, {data} = users
const handleChecked = (e) => {
const {value, checked} = e.target
checked ? setValues("roles", [...values.roles, value]) :
setValues("roles", roles.filter((e) => e !== value))
}
const [values, setValues] = useState({
//fields for the form
roles: []
})
<Table>
{data.map((user, I) => (
<tr key={i}>
{/* table data */}
</tr>
))}
</Table>
<ModalForm>
{/*form fields... */}
{roles.map((role, i) => (
<label key={i}>
<Checkox onChange={handleChecked} value={role.id} />
</label>
))}
</ModalForm>
And when I submit the form data, I get the result undefined in the console. I used this method in a previous project and it worked. For this case, I have a table (loads relationship roles from the backend) and a modal (with a create form) but in the previous project, I had a separate Create page to handle user input. So, I don't know whether it is a data conflict between the relationship roles of the table and the usePage() data roles.
This is in the index() method:
$search = $request->query('search');
return inertia('Admin/Users/Index', [
'users' => User::query()->when($search, fn($query) =>
$query->where('name', 'LIKE', "%{$search}%")
->orWhere('email', 'LIKE', "%{$search}%")
->orWhere('mobile_number', 'LIKE', "%{$search}%")
->orWhere('mobile_number_2', 'LIKE', "%{$search}%"))
->with('roles')->orderByDesc('created_at')->paginate(10)
->onEachSide(0)->withQueryString(),
'roles' => Role::get(),
]);
I've been stuck with this for hours today, and couldn't seem to get it done, even with a lot of googling.
Please or to participate in this conversation.