Next.js Discord

Discord Forum

Confirmation dialog for server action

Answered
Plott Hound posted this in #help-forum
Open in Discord
Plott HoundOP
Maybe i'm approaching this all wrong but here's an example of delete functionality for products:

<form action={handleDeleteProduct}>
  <input type="hidden" name="productId" value={product.id} />
  <Button type='submit'>Delete</Button>
</form>

which calls this action:
export async function handleDeleteProduct(formData: FormData) {
  const productId = formData.get('productId') as string;

  if (!productId) {
    throw new Error("Product ID is required for deletion.");
  }
  
  try {
    const deletedProduct = await prisma.product.delete({
      where: {
        id: productId,
      },
    });

    revalidatePath('/admin/products')

  } catch (error) {
    console.error(error);
    throw error;
  }
}


how can i add a confirmation dialog to this buttom / action? Am i using form actions correctly? thanks
Answered by Ray
 <form
      action={handleDeleteProduct}
      onSubmit={(e) => {
        e.preventDefault();
        const confimed = confirm("confirm?");
        if (confimed) {
          handleDeleteProduct(new FormData(e.currentTarget));
        }
      }}
    >
  ....
View full answer

6 Replies

Plott HoundOP
bump
 <form
      action={handleDeleteProduct}
      onSubmit={(e) => {
        e.preventDefault();
        const confimed = confirm("confirm?");
        if (confimed) {
          handleDeleteProduct(new FormData(e.currentTarget));
        }
      }}
    >
  ....
Answer
if the client have javascript enabled, it will use onSubmit event. Otherwise the action will be execute
or just use the onSubmit props
@Plott Hound thank you. im guessing i can only do this in a client component.
because of the nature of dialog on interaction, it needs to be client, so yes