diff --git a/src/components/create-url-dialog.tsx b/src/components/create-url-dialog.tsx index f1e322e..b298dab 100644 --- a/src/components/create-url-dialog.tsx +++ b/src/components/create-url-dialog.tsx @@ -3,7 +3,7 @@ import { getFormProps, getInputProps, useForm } from "@conform-to/react" import { getZodConstraint, parseWithZod } from "@conform-to/zod" import { nanoid } from "nanoid" -import { useActionState, useCallback } from "react" +import { useActionState, useCallback, useEffect, useRef } from "react" import { toast } from "sonner" import { Button } from "@/components/ui/button" import { @@ -41,20 +41,25 @@ export function CreateUrlDialog({ constraint: getZodConstraint(createUrlSchema), onValidate: ({ formData }) => parseWithZod(formData, { schema: createUrlSchema }), - onSubmit: () => { - if (error) { - console.error("Error creating URL:", error) - toast.error(`Error creating URL: ${error}`) - } else { - toast.success("Short URL created successfully!") - } - onSuccess() - }, - shouldValidate: "onBlur", shouldRevalidate: "onInput", }) + const onSuccessRef = useRef(onSuccess) + useEffect(() => { + onSuccessRef.current = onSuccess + }) + + useEffect(() => { + if (lastResult && !error) { + toast.success("Short URL created successfully!") + onSuccessRef.current() + } else if (lastResult && error) { + console.error("Error creating URL:", error) + toast.error(`Error creating URL: ${error}`) + } + }, [lastResult, error]) + const randomCode = useCallback(() => nanoid(8), []) const isRandom = !(fields.shortCode.value && fields.shortCode.valid) diff --git a/src/components/edit-url-dialog.tsx b/src/components/edit-url-dialog.tsx index d2e47e0..0c3dffd 100644 --- a/src/components/edit-url-dialog.tsx +++ b/src/components/edit-url-dialog.tsx @@ -2,7 +2,7 @@ import { getFormProps, getInputProps, useForm } from "@conform-to/react" import { getZodConstraint, parseWithZod } from "@conform-to/zod" -import { useActionState } from "react" +import { useActionState, useEffect, useRef } from "react" import { toast } from "sonner" import { Button } from "@/components/ui/button" import { @@ -48,19 +48,25 @@ export function EditUrlDialog({ constraint: getZodConstraint(editUrlSchema), onValidate: ({ formData }) => parseWithZod(formData, { schema: editUrlSchema }), - onSubmit: () => { - if (error) { - console.error("Error editing URL:", error) - toast.error(`Error editing URL: ${error}`) - } else { - toast.success("Short URL edited successfully!") - } - onSuccess() - }, shouldValidate: "onBlur", shouldRevalidate: "onInput", }) + const onSuccessRef = useRef(onSuccess) + useEffect(() => { + onSuccessRef.current = onSuccess + }) + + useEffect(() => { + if (lastResult && !error) { + toast.success("Short URL edited successfully!") + onSuccessRef.current() + } else if (lastResult && error) { + console.error("Error editing URL:", error) + toast.error(`Error editing URL: ${error}`) + } + }, [lastResult, error]) + return ( !open && onClose()}> {state.open && (