Skip to content

Commit

Permalink
Adding useSWRImmutable back to improve optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagoulloa committed Nov 15, 2024
1 parent b2de96c commit 14f45ab
Showing 1 changed file with 30 additions and 28 deletions.
58 changes: 30 additions & 28 deletions src/components/SearchModal/CurrencyList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import useHorizonLoadAccount from 'hooks/useHorizonLoadAccount';

import { isAddress, shortenAddress } from 'helpers/address';
import { formatTokenAmount } from 'helpers/format';
import useSWRImmutable from 'swr/immutable';

function currencyKey(currency: TokenType): string {
return currency.contract ? currency.contract : 'ETHER';
Expand Down Expand Up @@ -248,42 +249,43 @@ export default function CurrencyList({
const { tokenBalancesResponse } = useGetMyBalances();
const { account } = useHorizonLoadAccount();

const [balances, setBalances] = useState<Record<string, number>>({});

const itemData = useMemo(() => {
return otherListTokens && otherListTokens.length > 0
? [...currencies, ...otherListTokens]
: currencies;
}, [currencies, otherListTokens]);

useEffect(() => {
const fetchBalances = async () => {
const newBalances: Record<string, number> = {};

if (account) {
for (const currency of itemData) {
const balance = await getCurrencyBalance(
tokenBalancesResponse,
currency,
sorobanContext,
account,
);
newBalances[currencyKey(currency)] = Number(balance ?? 0);
}
setBalances(newBalances);
}
};
const fetchBalances = async () => {
if (
!account ||
!sorobanContext.activeChain ||
!sorobanContext.address ||
itemData.length === 0
) {
return {};
}

if (sorobanContext.activeChain && sorobanContext.address && account && itemData.length > 0) {
fetchBalances();
const newBalances: Record<string, number> = {};
for (const currency of itemData) {
const balance = await getCurrencyBalance(
tokenBalancesResponse,
currency,
sorobanContext,
account,
);
newBalances[currencyKey(currency)] = Number(balance ?? 0);
}
}, [
sorobanContext.activeChain,
sorobanContext.address,
account,
itemData,
tokenBalancesResponse,
]);
return newBalances;
};

const { data: balances = {}, error } = useSWRImmutable(
account ? ['balances', account, tokenBalancesResponse, itemData] : null,
fetchBalances,
);

if (error) {
console.error('Error loading balances:', error);
}

const sortedItemData = useMemo(() => {
if (!itemData || !Array.isArray(itemData)) {
Expand Down

0 comments on commit 14f45ab

Please sign in to comment.