Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add `useLinkBuilderSubmit`

Tim Wilson3f6a572283a1
diff --git a/apps/web/ui/links/link-builder/link-builder-provider.tsx b/apps/web/ui/links/link-builder/link-builder-provider.tsx
index 6b51b442e0..de3ee1232f 100644
--- a/apps/web/ui/links/link-builder/link-builder-provider.tsx
+++ b/apps/web/ui/links/link-builder/link-builder-provider.tsx
@@ -1,5 +1,5 @@
import { ExpandedLinkProps } from "@/lib/types";
-import { DEFAULT_LINK_PROPS } from "@dub/utils";
+import { DEFAULT_LINK_PROPS, PLANS } from "@dub/utils";
import {
createContext,
Dispatch,
@@ -16,18 +16,31 @@ export type LinkBuilderProps = {
props?: ExpandedLinkProps;
duplicateProps?: ExpandedLinkProps;
homepageDemo?: boolean;
- workspace?: { plan?: string; conversionEnabled?: boolean };
+ workspace: {
+ id?: string;
+ slug?: string;
+ plan?: string;
+ nextPlan?: (typeof PLANS)[number];
+ conversionEnabled?: boolean;
+ };
};
const LinkBuilderContext = createContext<
- LinkBuilderProps & {
- generatingMetatags: boolean;
- setGeneratingMetatags: Dispatch<SetStateAction<boolean>>;
- }
->({ generatingMetatags: false, setGeneratingMetatags: () => {} });
+ | (LinkBuilderProps & {
+ generatingMetatags: boolean;
+ setGeneratingMetatags: Dispatch<SetStateAction<boolean>>;
+ })
+ | null
+>(null);
export function useLinkBuilderContext() {
- return useContext(LinkBuilderContext);
+ const context = useContext(LinkBuilderContext);
+ if (!context)
+ throw new Error(
+ "useLinkBuilderContext must be used within a LinkBuilderProvider",
+ );
+
+ return context;
}
export function LinkBuilderProvider({
diff --git a/apps/web/ui/links/link-builder/use-link-builder-submit.tsx b/apps/web/ui/links/link-builder/use-link-builder-submit.tsx
new file mode 100644
index 0000000000..64ad63c97d
--- /dev/null
+++ b/apps/web/ui/links/link-builder/use-link-builder-submit.tsx
@@ -0,0 +1,130 @@
+import { mutatePrefix } from "@/lib/swr/mutate";
+import { UpgradeRequiredToast } from "@/ui/shared/upgrade-required-toast";
+import { useCopyToClipboard, useRouterStuff } from "@dub/ui";
+import posthog from "posthog-js";
+import { useCallback } from "react";
+import { useFormContext } from "react-hook-form";
+import { toast } from "sonner";
+import { mutate } from "swr";
+import { LinkFormData, useLinkBuilderContext } from "./link-builder-provider";
+
+export function useLinkBuilderSubmit({
+ onSuccess,
+}: {
+ onSuccess?: (data: LinkFormData) => void;
+} = {}) {
+ const { queryParams } = useRouterStuff();
+ const { workspace, props } = useLinkBuilderContext();
+ const { getValues, setError } = useFormContext<LinkFormData>();
+
+ const [, copyToClipboard] = useCopyToClipboard();
+
+ return useCallback(
+ async (data: LinkFormData) => {
+ // @ts-ignore – exclude extra attributes from `data` object before sending to API
+ const { user, tags, tagId, folderId, ...rest } = data;
+ const bodyData = {
+ ...rest,
+
+ // Map tags to tagIds
+ tagIds: tags.map(({ id }) => id),
+
+ // Replace "unsorted" folder ID w/ null
+ folderId: folderId === "unsorted" ? null : folderId,
+
+ // Manually reset empty strings to null
+ expiredUrl: rest.expiredUrl || null,
+ ios: rest.ios || null,
+ android: rest.android || null,
+ };
+
+ const endpoint = props?.id
+ ? {
+ method: "PATCH",
+ url: `/api/links/${props.id}?workspaceId=${workspace.id}`,
+ }
+ : {
+ method: "POST",
+ url: `/api/links?workspaceId=${workspace.id}`,
+ };
+
+ try {
+ const res = await fetch(endpoint.url, {
+ method: endpoint.method,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(bodyData),
+ });
+
+ if (res.status === 200) {
+ await mutatePrefix([
+ "/api/links",
+ // if updating root domain link, mutate domains as well
+ ...(getValues("key") === "_root" ? ["/api/domains"] : []),
+ ]);
+ const data = await res.json();
+ posthog.capture(props ? "link_updated" : "link_created", data);
+
+ // copy shortlink to clipboard when adding a new link
+ if (!props) {
+ try {
+ await copyToClipboard(data.shortLink);
+ toast.success("Copied short link to clipboard!");
+ } catch (err) {
+ toast.success("Successfully created link!");
+ }
+ } else toast.success("Successfully updated short link!");
+
+ onSuccess?.(data);
+
+ // Mutate workspace to update usage stats
+ mutate(`/api/workspaces/${workspace?.slug}`);
+
+ // Navigate to the link's folder
+ if (data.folderId) queryParams({ set: { folderId: data.folderId } });
+ else queryParams({ del: ["folderId"] });
+ } else {
+ const { error } = await res.json();
+
+ if (error) {
+ if (error.message.includes("Upgrade to")) {
+ toast.custom(() => (
+ <UpgradeRequiredToast
+ title={`You've discovered a ${workspace?.nextPlan?.name} feature!`}
+ message={error.message}
+ />
+ ));
+ } else {
+ toast.error(error.message);
+ }
+ const message = error.message.toLowerCase();
+
+ if (message.includes("key"))
+ setError("key", { message: error.message });
+ else if (message.includes("url"))
+ setError("url", { message: error.message });
+ else setError("root", { message: "Failed to save link" });
+ } else {
+ setError("root", { message: "Failed to save link" });
+ toast.error("Failed to save link");
+ }
+ }
+ } catch (e) {
+ setError("root", { message: "Failed to save link" });
+ console.error("Failed to save link", e);
+ toast.error("Failed to save link");
+ }
+ },
+ [
+ workspace.id,
+ workspace.slug,
+ workspace.nextPlan,
+ props,
+ copyToClipboard,
+ getValues,
+ setError,
+ onSuccess,
+ ],
+ );
+}
diff --git a/apps/web/ui/modals/link-builder/index.tsx b/apps/web/ui/modals/link-builder/index.tsx
index 5443cc49de..82e93d245f 100644
--- a/apps/web/ui/modals/link-builder/index.tsx
+++ b/apps/web/ui/modals/link-builder/index.tsx
@@ -1,6 +1,5 @@
"use client";
-import { mutatePrefix } from "@/lib/swr/mutate";
import useWorkspace from "@/lib/swr/use-workspace";
import { ExpandedLinkProps } from "@/lib/types";
import { FolderDropdown } from "@/ui/folders/folder-dropdown";
@@ -10,10 +9,10 @@ import {
LinkBuilderProvider,
useLinkBuilderContext,
} from "@/ui/links/link-builder/link-builder-provider";
+import { useLinkBuilderSubmit } from "@/ui/links/link-builder/use-link-builder-submit";
import { ShortLinkInput } from "@/ui/links/short-link-input";
import { useAvailableDomains } from "@/ui/links/use-available-domains";
import { X } from "@/ui/shared/icons";
-import { UpgradeRequiredToast } from "@/ui/shared/upgrade-required-toast";
import {
ArrowTurnLeft,
Button,
@@ -23,7 +22,6 @@ import {
Modal,
SimpleTooltipContent,
TooltipContent,
- useCopyToClipboard,
useEnterSubmit,
useKeyboardShortcut,
useRouterStuff,
@@ -37,8 +35,7 @@ import {
linkConstructor,
} from "@dub/utils";
import { ChevronRight } from "lucide-react";
-import { useParams, useSearchParams } from "next/navigation";
-import posthog from "posthog-js";
+import { useSearchParams } from "next/navigation";
import {
Dispatch,
SetStateAction,
@@ -50,8 +47,6 @@ import {
} from "react";
import { Controller, useFormContext } from "react-hook-form";
import TextareaAutosize from "react-textarea-autosize";
-import { toast } from "sonner";
-import { mutate } from "swr";
import { useDebounce } from "use-debounce";
import { ConversionTrackingToggle } from "./conversion-tracking-toggle";
import { DraftControls, DraftControlsHandle } from "./draft-controls";
@@ -98,11 +93,9 @@ function LinkBuilderInner({
showLinkBuilder,
setShowLinkBuilder,
}: LinkBuilderModalProps) {
- const params = useParams() as { slug?: string };
- const { slug } = params;
const searchParams = useSearchParams();
const { queryParams } = useRouterStuff();
- const { id: workspaceId, plan, nextPlan, logo, flags } = useWorkspace();
+ const { id: workspaceId, flags } = useWorkspace();
const { props, duplicateProps, homepageDemo } = useLinkBuilderContext();
@@ -111,7 +104,6 @@ function LinkBuilderInner({
watch,
handleSubmit,
setValue,
- setError,
clearErrors,
formState: { isDirty, isSubmitting, isSubmitSuccessful, errors },
} = useFormContext<LinkFormData>();
@@ -129,20 +121,6 @@ function LinkBuilderInner({
const [debouncedUrl] = useDebounce(getUrlWithoutUTMParams(url), 500);
- const endpoint = useMemo(
- () =>
- props?.id
- ? {
- method: "PATCH",
- url: `/api/links/${props.id}?workspaceId=${workspaceId}`,
- }
- : {
- method: "POST",
- url: `/api/links?workspaceId=${workspaceId}`,
- },
- [props, slug, domain, workspaceId],
- );
-
useMetatags({
initial: Boolean(props),
enabled: showLinkBuilder && debouncedUrl.length > 0,
@@ -199,7 +177,14 @@ function LinkBuilderInner({
const { TargetingModal, TargetingButton } = useTargetingModal();
const { PasswordModal, PasswordButton } = usePasswordModal();
- const [, copyToClipboard] = useCopyToClipboard();
+ const onSubmitSuccess = useCallback(() => {
+ draftControlsRef.current?.onSubmitSuccessful();
+ setShowLinkBuilder(false);
+ }, []);
+
+ const onSubmit = useLinkBuilderSubmit({
+ onSuccess: onSubmitSuccess,
+ });
return (
<>
@@ -219,97 +204,7 @@ function LinkBuilderInner({
draftControlsRef.current?.onClose();
}}
>
- <form
- ref={formRef}
- onSubmit={handleSubmit(async (data) => {
- // @ts-ignore – exclude extra attributes from `data` object before sending to API
- const { user, tags, tagId, folderId, ...rest } = data;
- const bodyData = {
- ...rest,
-
- // Map tags to tagIds
- tagIds: tags.map(({ id }) => id),
-
- // Replace "unsorted" folder ID w/ null
- folderId: folderId === "unsorted" ? null : folderId,
-
- // Manually reset empty strings to null
- expiredUrl: rest.expiredUrl || null,
- ios: rest.ios || null,
- android: rest.android || null,
- };
-
- try {
- const res = await fetch(endpoint.url, {
- method: endpoint.method,
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(bodyData),
- });
-
- if (res.status === 200) {
- await mutatePrefix([
- "/api/links",
- // if updating root domain link, mutate domains as well
- ...(key === "_root" ? ["/api/domains"] : []),
- ]);
- const data = await res.json();
- posthog.capture(props ? "link_updated" : "link_created", data);
-
- // copy shortlink to clipboard when adding a new link
- if (!props) {
- try {
- await copyToClipboard(data.shortLink);
- toast.success("Copied short link to clipboard!");
- } catch (err) {
- toast.success("Successfully created link!");
- }
- } else toast.success("Successfully updated short link!");
-
- draftControlsRef.current?.onSubmitSuccessful();
- setShowLinkBuilder(false);
-
- // Mutate workspace to update usage stats
- mutate(`/api/workspaces/${slug}`);
-
- // Navigate to the link's folder
- if (data.folderId)
- queryParams({ set: { folderId: data.folderId } });
- else queryParams({ del: ["folderId"] });
- } else {
- const { error } = await res.json();
-
- if (error) {
- if (error.message.includes("Upgrade to")) {
- toast.custom(() => (
- <UpgradeRequiredToast
- title={`You've discovered a ${nextPlan.name} feature!`}
- message={error.message}
- />
- ));
- } else {
- toast.error(error.message);
- }
- const message = error.message.toLowerCase();
-
- if (message.includes("key"))
- setError("key", { message: error.message });
- else if (message.includes("url"))
- setError("url", { message: error.message });
- else setError("root", { message: "Failed to save link" });
- } else {
- setError("root", { message: "Failed to save link" });
- toast.error("Failed to save link");
- }
- }
- } catch (e) {
- setError("root", { message: "Failed to save link" });
- console.error("Failed to save link", e);
- toast.error("Failed to save link");
- }
- })}
- >
+ <form ref={formRef} onSubmit={handleSubmit(onSubmit)}>
<div className="flex flex-col items-start gap-2 px-6 py-4 md:flex-row md:items-center md:justify-between">
{flags?.linkFolders && (
<div className="flex items-center gap-2">