I have the following component, and it has alert dialog inside and async task.
I want the alert dialog to close only after async task has been done, or what is the best practice behaviour?
the alert dialog is triggered from a table from which you need to decline/accepet something (and then router.refresh() for triggering new fetch data for the table)
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { makeServerRequestFromClient } from "@/shared/lib/api";
const ApproveDeclineMeeting = (meetingId: string) => {
const [isApproved, setIsApproved] = useState(false);
const router = useRouter();
const status = isApproved ? "Active" : "Not approved";
const [open, setOpen] = useState(false);
const handleAction = (approveValue: boolean) => {
setIsApproved(approveValue);
setOpen(true);
};
const onSubmit = async () => {
try {
const URI = `meeting/${meetingId}`;
const body = { status: status };
const method = "PUT";
const res = await makeServerRequestFromClient({ URI, body, method });
if (res.ok) {
toast.success("");
}
router.refresh();
} catch (err) {
setOpen(true);
toast.error("");
}
};
return (
<>
<Button
variant="destructive"
onClick={() => handleAction(true)}
className="bg-green2 hover:bg-green2/80"
>
Approve
</Button>
<Button
variant="destructive"
className="mr-2"
onClick={() => handleAction(false)}
>
Decline
</Button>
<AlertDialog
open={open}
onOpenChange={() => setOpen((prevOpen) => !prevOpen)}
>
<AlertDialogTrigger asChild></AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete your
account and remove your data from our servers.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={onSubmit}>Continue</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
};
export default ApproveDeclineMeeting;