Skip to content

Commit

Permalink
Merge branch '474-refactor-the-token-map-hook-to-enhance-efficiency' …
Browse files Browse the repository at this point in the history
…into 'dev'

Resolve "Refactor the token map hook to enhance efficiency"

Closes #474

See merge request ergo/rosen-bridge/ui!395
  • Loading branch information
vorujack committed Dec 23, 2024
2 parents 0d101cf + a4f7b6b commit fc388e2
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 24 deletions.
5 changes: 5 additions & 0 deletions .changeset/loud-windows-count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@rosen-bridge/rosen-app': patch
---

Refactor the token map hook to enhance efficiency
5 changes: 4 additions & 1 deletion apps/rosen/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@ import { App as AppBase } from '@rosen-bridge/ui-kit';
import { theme } from '@/_theme/theme';

import { WalletContextProvider } from './_contexts/walletContext';
import { TokenMapProvider } from './_hooks';
import { SideBar } from './SideBar';
import { Toolbar } from './Toolbar';

export const App = ({ children }: { children?: React.ReactNode }) => {
return (
<NoSsr>
<AppBase sideBar={<SideBar />} theme={theme} toolbar={<Toolbar />}>
<WalletContextProvider>{children}</WalletContextProvider>
<TokenMapProvider>
<WalletContextProvider>{children}</WalletContextProvider>
</TokenMapProvider>
</AppBase>
</NoSsr>
);
Expand Down
23 changes: 0 additions & 23 deletions apps/rosen/app/_hooks/useTokenMap.ts

This file was deleted.

55 changes: 55 additions & 0 deletions apps/rosen/app/_hooks/useTokenMap.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import {
ReactNode,
createContext,
useContext,
useEffect,
useState,
useTransition,
} from 'react';

import { TokenMap } from '@rosen-bridge/tokens';

import { getTokenMap } from '@/_tokenMap/getClientTokenMap';

/**
* return TokenMap instance
*/
export const useTokenMap = () => {
const context = useContext(TokenMapContext);

if (!context) {
throw new Error('useTokenMap must be used within TokenMapProvider');
}

return context;
};

export type TokenMapContextType = TokenMap;

export const TokenMapContext = createContext<TokenMap | null>(null);

export const TokenMapProvider = ({ children }: { children: ReactNode }) => {
const [tokenMap, setTokenMap] = useState(
new TokenMap({ idKeys: {}, tokens: [] }),
);

const [, startTransition] = useTransition();

useEffect(() => {
startTransition(async () => {
try {
setTokenMap(await getTokenMap());
} catch (error) {
throw new Error('Failed to fetch TokenMap, reload the page.', {
cause: error,
});
}
});
}, []);

return (
<TokenMapContext.Provider value={tokenMap}>
{children}
</TokenMapContext.Provider>
);
};

0 comments on commit fc388e2

Please sign in to comment.