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 useApiRequest hook and integrate with bounty sheet

Kiran K3c5d85eabb89
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx
index 7ca2ae17f5..31289b4225 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/bounties/add-edit-bounty-sheet.tsx
@@ -11,6 +11,7 @@ import {
} from "@/ui/partners/program-sheet-accordion";
import { AmountInput } from "@/ui/shared/amount-input";
import { X } from "@/ui/shared/icons";
+import { useApiRequest } from "@/ui/shared/use-api-mutation";
import {
AnimatedSizeContainer,
Button,
@@ -59,6 +60,7 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
const [requireImage, setRequireImage] = useState(false);
const [requireUrl, setRequireUrl] = useState(false);
const [openAccordions, setOpenAccordions] = useState(ACCORDION_ITEMS);
+ const { makeRequest, loading } = useApiRequest();
const {
handleSubmit,
@@ -81,14 +83,14 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
"description",
]);
- // make sure endsAt is null if hasEndDate is false
+ // Make sure endsAt is null if hasEndDate is false
useEffect(() => {
if (!hasEndDate) {
setValue("endsAt", null);
}
}, [hasEndDate, setValue]);
- // set submission requirements
+ // Set submission requirements
useEffect(() => {
const requirements: SubmissionRequirement[] = [];
@@ -107,7 +109,7 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
}
}, [requireImage, requireUrl, setValue]);
- // decide if the submit button should be disabled
+ // Decide if the submit button should be disabled
const shouldDisableSubmit = useMemo(() => {
if (!startsAt || !rewardAmount) {
return true;
@@ -120,12 +122,20 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
return false;
}, [startsAt, rewardAmount, type, name]);
+ // Handle form submission
const onSubmit = async (data: FormData) => {
if (!workspaceId) {
return;
}
- console.log(data);
+ await makeRequest("/api/bounties", {
+ method: "POST",
+ body: data,
+ successMessage: "Bounty created successfully!",
+ onSuccess: () => {
+ setIsOpen(false);
+ },
+ });
};
return (
@@ -400,7 +410,7 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
onClick={() => setIsOpen(false)}
text="Cancel"
className="w-fit"
- // disabled={isPending}
+ disabled={loading}
/>
<Button
@@ -408,8 +418,13 @@ function BountySheetContent({ setIsOpen }: BountySheetProps) {
variant="primary"
text="Create bounty"
className="w-fit"
- // loading={isPending}
+ loading={loading}
disabled={shouldDisableSubmit}
+ disabledTooltip={
+ shouldDisableSubmit
+ ? "Please fill all required fields."
+ : undefined
+ }
/>
</div>
</div>
diff --git a/apps/web/ui/shared/use-api-mutation.ts b/apps/web/ui/shared/use-api-mutation.ts
new file mode 100644
index 0000000000..36341846e6
--- /dev/null
+++ b/apps/web/ui/shared/use-api-mutation.ts
@@ -0,0 +1,125 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import { useCallback, useState } from "react";
+import { toast } from "sonner";
+
+interface ApiRequestOptions<TBody> {
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
+ body?: TBody;
+ headers?: Record<string, string>;
+ showToast?: boolean;
+ successMessage?: string;
+ onSuccess?: () => void;
+ onError?: () => void;
+}
+
+interface ApiResponse<T> {
+ data: T | null;
+ error: string | null;
+ loading: boolean;
+ makeRequest: (
+ endpoint: string,
+ options?: ApiRequestOptions<any>,
+ ) => Promise<void>;
+}
+
+interface ApiError {
+ error: {
+ message: string;
+ };
+}
+
+const debug = (...args: any[]) => {
+ if (process.env.NODE_ENV === "development") {
+ console.log(...args);
+ }
+};
+
+export function useApiRequest<
+ 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 [loading, setLoading] = useState(false);
+
+ const makeRequest = useCallback(
+ async (endpoint: string, options: ApiRequestOptions<TBody> = {}) => {
+ const {
+ method = "GET",
+ body,
+ headers,
+ successMessage,
+ showToast = true,
+ onSuccess,
+ onError,
+ } = options;
+
+ setLoading(true);
+ setError(null);
+ setData(null);
+
+ try {
+ debug("Starting request", {
+ endpoint,
+ method,
+ body,
+ headers,
+ });
+
+ const response = await fetch(`${endpoint}?workspaceId=${workspaceId}`, {
+ method,
+ headers: {
+ "Content-Type": "application/json",
+ ...headers,
+ },
+ 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);
+ onSuccess?.();
+
+ if (showToast) {
+ toast.success(successMessage || "Request completed successfully.");
+ }
+
+ debug("Response received", data);
+ } catch (error) {
+ setError(
+ error instanceof Error
+ ? error.message
+ : "Something went wrong. Please try again.",
+ );
+
+ onError?.();
+
+ if (showToast) {
+ toast.error(error.message);
+ }
+
+ debug("Error occurred", error);
+ } finally {
+ setLoading(false);
+ debug("Request finished");
+ }
+ },
+ [],
+ );
+
+ return {
+ data,
+ error,
+ loading,
+ makeRequest,
+ };
+}