diff --git a/frontend/src/components/hosted/AppContainer.tsx b/frontend/src/components/hosted/AppContainer.tsx index f081d29..06a04d6 100644 --- a/frontend/src/components/hosted/AppContainer.tsx +++ b/frontend/src/components/hosted/AppContainer.tsx @@ -1,14 +1,19 @@ import { SignUp, UserButton, useUser } from "@clerk/clerk-react"; import App from "../../App"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { AlertDialog } from "@radix-ui/react-alert-dialog"; import { AlertDialogContent } from "../ui/alert-dialog"; import FullPageSpinner from "../custom-ui/FullPageSpinner"; +import { useAuthenticatedFetch } from "./useAuthenticatedFetch"; function AppContainer() { const [showPopup, setShowPopup] = useState(false); const { isSignedIn, isLoaded } = useUser(); + // For fetching user + const authenticatedFetch = useAuthenticatedFetch(); + const isInitRequestInProgress = useRef(false); + // If Clerk is loaded and the user is not signed in, show the sign up popup useEffect(() => { if (isLoaded && !isSignedIn) { @@ -16,6 +21,27 @@ function AppContainer() { } }, [isSignedIn, isLoaded]); + // Get the current user + useEffect(() => { + const init = async () => { + // Make sure there's only one request in progress + // so that we don't create multiple users + if (isInitRequestInProgress.current) return; + isInitRequestInProgress.current = true; + + const user = await authenticatedFetch( + // "https://screenshot-to-code-saas.onrender.com/users/create", + "http://localhost:8001/users/create", + "POST" + ); + console.log(user); + + isInitRequestInProgress.current = false; + }; + + init(); + }, []); + // If Clerk is still loading, show a spinner if (!isLoaded) return ; diff --git a/frontend/src/components/hosted/useAuthenticatedFetch.ts b/frontend/src/components/hosted/useAuthenticatedFetch.ts new file mode 100644 index 0000000..0aaae3b --- /dev/null +++ b/frontend/src/components/hosted/useAuthenticatedFetch.ts @@ -0,0 +1,39 @@ +import { useAuth } from "@clerk/clerk-react"; + +type FetchMethod = "GET" | "POST" | "PUT" | "DELETE"; + +export const useAuthenticatedFetch = () => { + const { getToken } = useAuth(); + + const authenticatedFetch = async ( + url: string, + method: FetchMethod = "GET", + body: object | null | undefined = null + ) => { + const accessToken = await getToken(); + const headers: HeadersInit = { + "Content-Type": "application/json", + Authorization: `Bearer ${accessToken}`, + }; + + const options: RequestInit = { + method, + headers, + }; + + if (body) { + options.body = JSON.stringify(body); + } + + const response = await fetch(url, options); + + if (!response.ok) { + throw new Error(`HTTP error ${response.status}: ${response.statusText}`); + } + + const json = await response.json(); + return json; + }; + + return authenticatedFetch; +};