From e6570dd7ec5d7aea3c3d0c0235476a1227bbe71f Mon Sep 17 00:00:00 2001
From: MohamedBassem <me@mbassem.com>
Date: Tue, 5 Mar 2024 18:27:38 +0000
Subject: extension: Instead of manually creating api keys, let users exchange
 their username passwords for one

---
 packages/browser-extension/src/utils/providers.tsx | 47 ++++++++++++----------
 1 file changed, 25 insertions(+), 22 deletions(-)

(limited to 'packages/browser-extension/src/utils/providers.tsx')

diff --git a/packages/browser-extension/src/utils/providers.tsx b/packages/browser-extension/src/utils/providers.tsx
index cf3ca804..d21714b6 100644
--- a/packages/browser-extension/src/utils/providers.tsx
+++ b/packages/browser-extension/src/utils/providers.tsx
@@ -1,35 +1,38 @@
 import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
 import { httpBatchLink } from "@trpc/client";
-import { useCallback, useEffect, useState } from "react";
+import { useEffect, useState } from "react";
 import { api } from "./trpc";
-import usePluginSettings from "./settings";
+import usePluginSettings, { getPluginSettings } from "./settings";
 import superjson from "superjson";
 
+function getTRPCClient(address: string) {
+  return api.createClient({
+    links: [
+      httpBatchLink({
+        url: `${address}/api/trpc`,
+        async headers() {
+          const settings = await getPluginSettings();
+          return {
+            Authorization: `Bearer ${settings.apiKey}`,
+          };
+        },
+        transformer: superjson,
+      }),
+    ],
+  });
+}
+
 export function Providers({ children }: { children: React.ReactNode }) {
-  const [settings] = usePluginSettings();
+  const { settings } = usePluginSettings();
   const [queryClient] = useState(() => new QueryClient());
 
-  const getTrpcClient = useCallback(() => {
-    return api.createClient({
-      links: [
-        httpBatchLink({
-          url: `${settings.address}/api/trpc`,
-          headers() {
-            return {
-              Authorization: `Bearer ${settings.apiKey}`,
-            };
-          },
-          transformer: superjson,
-        }),
-      ],
-    });
-  }, [settings]);
-
-  const [trpcClient, setTrpcClient] = useState(getTrpcClient());
+  const [trpcClient, setTrpcClient] = useState<
+    ReturnType<typeof getTRPCClient>
+  >(getTRPCClient(settings.address));
 
   useEffect(() => {
-    setTrpcClient(getTrpcClient());
-  }, [getTrpcClient]);
+    setTrpcClient(getTRPCClient(settings.address));
+  }, [settings.address]);
 
   return (
     <api.Provider client={trpcClient} queryClient={queryClient}>
-- 
cgit v1.2.3-70-g09d2

