"use client"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { addDevice } from "@/queries/devices"; import { tryCatch } from "@/utils/tryCatch"; import { zodResolver } from "@hookform/resolvers/zod"; import { Loader2, Plus } from "lucide-react"; import { useState } from "react"; import { type SubmitHandler, useForm } from "react-hook-form"; import { toast } from "sonner"; import { z } from "zod"; export default function AddDeviceDialogForm({ user_id }: { user_id?: string }) { const formSchema = z.object({ name: z.string().min(2, { message: "Name is required." }), mac_address: z .string() .min(2, { message: "MAC Address is required." }) .regex( /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/, "Please enter a valid MAC address", ), }); const [disabled, setDisabled] = useState(false); const [open, setOpen] = useState(false); const { register, handleSubmit, reset, formState: { errors }, } = useForm>({ resolver: zodResolver(formSchema), }); if (!user_id) { return null; } const onSubmit: SubmitHandler> = async (data) => { console.log(data); setDisabled(true); const [error, response] = await tryCatch( addDevice({ mac: data.mac_address, name: data.name, }), ); if (error) { toast.error(error.message || "Something went wrong."); setDisabled(false); } else { console.log(response); setOpen(false); setDisabled(false); toast.success("Device successfully added!"); reset(); } }; return ( New Device To add a new device, enter the device name and mac address below. Click save when you are done.
{errors.name?.message}
{errors.mac_address?.message}
); }