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.

Refactor group creation to use useApiMutation hook

Kiran K702b06d24a8a
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/groups/create-group-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/groups/create-group-sheet.tsx
index 5516d20bc4..fc4f4f751a 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/groups/create-group-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/groups/create-group-sheet.tsx
@@ -1,3 +1,4 @@
+import { useApiMutation } from "@/lib/swr/use-api-mutation";
import useWorkspace from "@/lib/swr/use-workspace";
import { createGroupSchema } from "@/lib/zod/schemas/groups";
import { X } from "@/ui/shared/icons";
@@ -16,7 +17,7 @@ type FormData = z.input<typeof createGroupSchema>;
function CreateGroupSheetContent({ setIsOpen }: CreateGroupSheetProps) {
const { id: workspaceId } = useWorkspace();
- const [isSubmitting, setIsSubmitting] = useState(false);
+ const { makeRequest, isSubmitting } = useApiMutation();
const {
register,
@@ -25,20 +26,23 @@ function CreateGroupSheetContent({ setIsOpen }: CreateGroupSheetProps) {
formState: { errors },
} = useForm<FormData>();
- const [name] = watch(["name"]);
-
const onSubmit = async (data: FormData) => {
if (!workspaceId) {
return;
}
- setIsSubmitting(true);
-
- console.log(data);
-
- toast.success("Group created successfully!");
- setIsOpen(false);
- setIsSubmitting(false);
+ await makeRequest("/api/groups", {
+ method: "POST",
+ body: {
+ ...data,
+ slug: data.name.toLowerCase(),
+ color: "##0000"
+ },
+ onSuccess: () => {
+ toast.success("Group created successfully!");
+ setIsOpen(false);
+ },
+ });
};
return (
@@ -65,7 +69,7 @@ function CreateGroupSheetContent({ setIsOpen }: CreateGroupSheetProps) {
htmlFor="name"
className="text-sm font-medium text-neutral-800"
>
- Group name
+ Name
</label>
<div className="mt-2">
<input
@@ -77,9 +81,9 @@ function CreateGroupSheetContent({ setIsOpen }: CreateGroupSheetProps) {
"border-red-600 focus:border-red-500 focus:ring-red-600",
)}
{...register("name", {
- required: "Group name is required",
+ required: "Nme is required",
})}
- placeholder="Enter group name"
+ placeholder="Group name"
/>
{errors.name && (
<p className="mt-1 text-sm text-red-600">
diff --git a/apps/web/lib/api/groups/get-groups.ts b/apps/web/lib/api/groups/get-groups.ts
index b7cfe7d130..b3bc59d627 100644
--- a/apps/web/lib/api/groups/get-groups.ts
+++ b/apps/web/lib/api/groups/get-groups.ts
@@ -8,7 +8,7 @@ type GroupFilters = z.infer<typeof getGroupsQuerySchema> & {
};
const sortColumnsMap = {
- createdAt: "createdAt",
+ createdAt: "pg.createdAt",
clicks: "totalClicks",
leads: "totalLeads",
conversions: "totalConversions",
diff --git a/apps/web/lib/swr/use-api-mutation.ts b/apps/web/lib/swr/use-api-mutation.ts
index 759c2512ef..5bd3755411 100644
--- a/apps/web/lib/swr/use-api-mutation.ts
+++ b/apps/web/lib/swr/use-api-mutation.ts
@@ -1,14 +1,12 @@
+import useWorkspace from "@/lib/swr/use-workspace";
import { useCallback, useState } from "react";
import { toast } from "sonner";
-import useWorkspace from "./use-workspace";
interface ApiRequestOptions<TBody> {
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
body?: TBody;
headers?: Record<string, string>;
- debug?: boolean;
showToast?: boolean;
- successMessage?: string;
onSuccess?: () => void;
onError?: () => void;
}
@@ -16,7 +14,7 @@ interface ApiRequestOptions<TBody> {
interface ApiResponse<T> {
data: T | null;
error: string | null;
- isLoading: boolean;
+ isSubmitting: boolean;
makeRequest: (
endpoint: string,
options?: ApiRequestOptions<any>,
@@ -29,14 +27,20 @@ interface ApiError {
};
}
-export function useApiRequest<
+const debug = (...args: any[]) => {
+ if (process.env.NODE_ENV === "development") {
+ console.log(...args);
+ }
+};
+
+export function useApiMutation<
TResponse = any,
TBody = any,
>(): ApiResponse<TResponse> {
const { id: workspaceId } = useWorkspace();
const [data, setData] = useState<TResponse | null>(null);
const [error, setError] = useState<string | null>(null);
- const [isLoading, setIsLoading] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
const makeRequest = useCallback(
async (endpoint: string, options: ApiRequestOptions<TBody> = {}) => {
@@ -44,30 +48,24 @@ export function useApiRequest<
method = "GET",
body,
headers,
- successMessage,
- debug = false,
showToast = true,
onSuccess,
onError,
} = options;
- setIsLoading(true);
+ setIsSubmitting(true);
setError(null);
setData(null);
try {
- if (debug) {
- console.log("[useApiRequest] Starting request", {
- endpoint,
- method,
- body,
- headers,
- });
- }
-
- const finalEndpoint = `${endpoint}?workspaceId=${workspaceId}`;
+ debug("Starting request", {
+ endpoint,
+ method,
+ body,
+ headers,
+ });
- const response = await fetch(finalEndpoint, {
+ const response = await fetch(`${endpoint}?workspaceId=${workspaceId}`, {
method,
headers: {
"Content-Type": "application/json",
@@ -76,27 +74,20 @@ export function useApiRequest<
body: body ? JSON.stringify(body) : undefined,
});
+ // Handle error
if (!response.ok) {
const { error } = (await response.json()) as ApiError;
-
throw new Error(
error.message || `Request failed with status ${response.status}`,
);
}
+ // Handle success
const data = (await response.json()) as TResponse;
-
setData(data);
-
- if (debug) {
- console.log("[useApiRequest] Response received", data);
- }
-
onSuccess?.();
- if (showToast) {
- toast.success(successMessage || "Request completed successfully.");
- }
+ debug("Response received", data);
} catch (error) {
setError(
error instanceof Error
@@ -104,25 +95,25 @@ export function useApiRequest<
: "Something went wrong. Please try again.",
);
- if (debug) {
- console.error("[useApiRequest] Error occurred", error);
- }
-
onError?.();
if (showToast) {
toast.error(error.message);
}
- } finally {
- setIsLoading(false);
- if (debug) {
- console.log("[useApiRequest] Request finished");
- }
+ debug("Error occurred", error);
+ } finally {
+ setIsSubmitting(false);
+ debug("Request finished");
}
},
[],
);
- return { data, error, isLoading, makeRequest };
-}
+ return {
+ data,
+ error,
+ isSubmitting,
+ makeRequest,
+ };
+}
\ No newline at end of file