"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 { Loader2, Plus } from "lucide-react"; import { useActionState, useEffect, useState } from "react"; // Import useActionState import { toast } from "sonner"; import { GetMacAccordion } from "../how-to-get-mac"; import { addDeviceAction } from "@/queries/devices"; export type AddDeviceFormState = { message: string; fieldErrors?: { name?: string[]; mac_address?: string[]; }; payload?: FormData; }; export const initialState: AddDeviceFormState = { message: "", fieldErrors: {}, }; export default function AddDeviceDialogForm({ user_id }: { user_id?: string }) { const [open, setOpen] = useState(false); const [state, formAction, pending] = useActionState( addDeviceAction, initialState ); useEffect(() => { if (state.message && state !== initialState) { if (state.fieldErrors && Object.keys(state.fieldErrors).length > 0) { toast.error(state.message); } else if (state.message.includes("success")) { toast.success(state.message); setOpen(false); } else { toast.error(state.message); } } }, [state]); if (!user_id) { return null; } return ( New Device To add a new device, enter the device name and mac address below. Click save when you are done.
{state.fieldErrors?.name && ( {state.fieldErrors.name[0]} )}
{state.fieldErrors?.mac_address && ( {state.fieldErrors.mac_address[0]} )}
); }