From f3996ba7efe06d510791438be064020421dbb195 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lcio=20Franco?= Date: Thu, 9 Jan 2025 21:53:44 +0800 Subject: [PATCH] feat: add useConnection --- .../src/systems/CRX/hooks/useCurrentTab.ts | 16 ++------- .../src/systems/DApp/hooks/useConnection.ts | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 14 deletions(-) create mode 100644 packages/app/src/systems/DApp/hooks/useConnection.ts diff --git a/packages/app/src/systems/CRX/hooks/useCurrentTab.ts b/packages/app/src/systems/CRX/hooks/useCurrentTab.ts index 1fdba36dc..cb8fa06f7 100644 --- a/packages/app/src/systems/CRX/hooks/useCurrentTab.ts +++ b/packages/app/src/systems/CRX/hooks/useCurrentTab.ts @@ -9,20 +9,8 @@ export function useCurrentTab() { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { const currentTab = tabs[0]; - - if (currentTab?.url) { - const faviconUrl = currentTab.favIconUrl; - setFaviconUrl(faviconUrl); - - try { - const url = new URL(currentTab.url); - const port = url.port ? `:${url.port}` : ''; - const result = `${url.protocol}//${url.hostname}${port}`; - setOrigin(result); - } catch (_e) { - setOrigin(undefined); - } - } + setFaviconUrl(currentTab?.favIconUrl); + setOrigin(currentTab?.url); }); }, []); diff --git a/packages/app/src/systems/DApp/hooks/useConnection.ts b/packages/app/src/systems/DApp/hooks/useConnection.ts new file mode 100644 index 000000000..68cec0e27 --- /dev/null +++ b/packages/app/src/systems/DApp/hooks/useConnection.ts @@ -0,0 +1,34 @@ +import type { Connection } from '@fuel-wallet/types'; +import { useEffect, useState } from 'react'; +import { ConnectionService } from '../services'; + +interface UseConnectionProps { + url: string | undefined; +} + +const parseUrl = (url: string): string | undefined => { + try { + const { protocol, hostname, port } = new URL(url); + return `${protocol}//${hostname}${port ? `:${port}` : ''}`; + } catch (_e) { + return undefined; + } +}; + +export const useConnection = ({ url = '' }: UseConnectionProps) => { + const [connection, setConnection] = useState(); + + useEffect(() => { + const fetchConnection = async () => { + const origin = parseUrl(url); + const existingConnection = await ConnectionService.getConnection(origin); + setConnection(existingConnection); + }; + + fetchConnection(); + }, [url]); + + return { + connection, + }; +};