Skip to content

Commit

Permalink
fix: near render loop issue
Browse files Browse the repository at this point in the history
  • Loading branch information
kyranjamie authored and fbwoolf committed Jan 31, 2022
1 parent 4e372e4 commit e60d527
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 71 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
"react-dom": "17.0.2",
"react-hot-toast": "2.0.0",
"react-icons": "4.3.1",
"react-query": "3.34.7",
"react-query": "3.34.12",
"react-router-dom": "6.2.1",
"react-virtuoso": "2.5.1",
"svg-url-loader": "7.1.1",
Expand Down
26 changes: 13 additions & 13 deletions src/app/common/hooks/account/use-account-names.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { Account } from '@stacks/wallet-sdk';
import { useMemo } from 'react';

import { useCurrentAccount } from '@app/store/accounts/account.hooks';
import { useAllAccountNames, useCurrentAccountNames } from '@app/query/bns/bns.hooks';
import { useCurrentAccountNames, useGetAccountNamesByAddressQuery } from '@app/query/bns/bns.hooks';

export function useCurrentAccountDisplayName() {
const names = useCurrentAccountNames();
const account = useCurrentAccount();
if (!account || typeof account?.index !== 'number') return 'Account';
return names?.[0] || `Account ${account?.index + 1}`;
return useMemo(() => {
if (!account || typeof account?.index !== 'number') return 'Account';
return names?.[0] || `Account ${account?.index + 1}`;
}, [account, names]);
}

export function useAccountDisplayName(providedAccount?: Account) {
// if we don't pass an account, we should use this
// as it will only fetch the single name if we need it
const accountDisplayName = useCurrentAccountDisplayName();
const names = useAllAccountNames();
const account = providedAccount;
export function useAccountDisplayName(address: string, index: number) {
const names = useGetAccountNamesByAddressQuery(address);

if (!providedAccount) return accountDisplayName;
if (!account || typeof account?.index !== 'number') return 'Account';
return names?.[account.index]?.names?.[0] || `Account ${account?.index + 1}`;
return useMemo(() => {
if (!names.length) return `Account ${index + 1}`;
return names[0];
}, [index, names]);
}
15 changes: 10 additions & 5 deletions src/app/components/account-balance-caption.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@ import { stacksValue } from '@app/common/stacks-utils';
import { Caption, Text } from '@app/components/typography';
import { color } from '@stacks/ui';
import BigNumber from 'bignumber.js';
import { useMemo } from 'react';

interface AccountBalanceCaptionProps {
availableBalance?: BigNumber;
}
export function AccountBalanceCaption({ availableBalance }: AccountBalanceCaptionProps) {
const balance = stacksValue({
value: availableBalance || 0,
withTicker: true,
abbreviate: true,
});
const balance = useMemo(
() =>
stacksValue({
value: availableBalance || 0,
withTicker: true,
abbreviate: true,
}),
[availableBalance]
);

return (
<>
Expand Down
6 changes: 3 additions & 3 deletions src/app/pages/choose-account/choose-account.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { memo, useCallback, useEffect } from 'react';
import { Stack, Text } from '@stacks/ui';
import { Flex, Stack, Text } from '@stacks/ui';

import { useRouteHeader } from '@app/common/hooks/use-route-header';
import { Title } from '@app/components/typography';
Expand All @@ -25,7 +25,7 @@ export const ChooseAccount = memo(() => {
}, [handleUnmount]);

return (
<>
<Flex flexDirection="column">
<Stack spacing="loose" textAlign="center">
<AppIcon mt="extra-loose" mb="loose" size="72px" />
<Stack spacing="base">
Expand All @@ -34,6 +34,6 @@ export const ChooseAccount = memo(() => {
</Stack>
</Stack>
<Accounts />
</>
</Flex>
);
});
39 changes: 23 additions & 16 deletions src/app/pages/choose-account/components/accounts.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback, Suspense, memo, useState, useMemo } from 'react';
import { useCallback, Suspense, memo, useState, useMemo, useEffect } from 'react';
import { FiPlusCircle } from 'react-icons/fi';
import { Box, BoxProps, color, FlexProps, Spinner, Stack } from '@stacks/ui';
import { Box, BoxProps, color, Flex, FlexProps, Spinner, Stack } from '@stacks/ui';
import { Virtuoso } from 'react-virtuoso';

import { Caption, Text, Title } from '@app/components/typography';
Expand All @@ -25,10 +25,10 @@ import { useAddressAvailableStxBalance } from '@app/query/balance/balance.hooks'
const loadingProps = { color: '#A1A7B3' };
const getLoadingProps = (loading: boolean) => (loading ? loadingProps : {});

const AccountTitlePlaceholder = ({
account,
...rest
}: { account: AccountWithAddress } & BoxProps) => {
interface AccountTitlePlaceholderProps extends BoxProps {
account: AccountWithAddress;
}
const AccountTitlePlaceholder = ({ account, ...rest }: AccountTitlePlaceholderProps) => {
const name = `Account ${account?.index + 1}`;
return (
<Title fontSize={2} lineHeight="1rem" fontWeight="400" {...rest}>
Expand All @@ -37,8 +37,11 @@ const AccountTitlePlaceholder = ({
);
};

const AccountTitle = ({ account, ...rest }: { account: AccountWithAddress } & BoxProps) => {
const name = useAccountDisplayName(account);
interface AccountTitleProps extends BoxProps {
account: AccountWithAddress;
name: string;
}
const AccountTitle = ({ account, name, ...rest }: AccountTitleProps) => {
return (
<Title fontSize={2} lineHeight="1rem" fontWeight="400" {...rest}>
{name}
Expand All @@ -52,12 +55,11 @@ interface AccountItemProps extends FlexProps {
account: AccountWithAddress;
onSelectAccount(index: number): void;
}

const AccountItem = memo((props: AccountItemProps) => {
const { selectedAddress, account, isLoading, onSelectAccount, ...rest } = props;
const [component, bind] = usePressable(true);
const { decodedAuthRequest } = useOnboardingState();
const name = useAccountDisplayName(account);
const name = useAccountDisplayName(account.address, account.index);
const availableStxBalance = useAddressAvailableStxBalance(account.address);
const showLoadingProps = !!selectedAddress || !decodedAuthRequest;

Expand All @@ -83,15 +85,21 @@ const AccountItem = memo((props: AccountItemProps) => {
/>
}
>
<AccountTitle {...getLoadingProps(showLoadingProps)} account={account} />
<AccountTitle
name={name}
{...getLoadingProps(showLoadingProps)}
account={account}
/>
</Suspense>
<Stack alignItems="center" spacing="6px" isInline>
<Caption fontSize={0} {...getLoadingProps(showLoadingProps)}>
{truncateMiddle(account.address, 4)}
</Caption>
<Suspense fallback={<></>}>
<AccountBalanceCaption availableBalance={availableStxBalance} />
</Suspense>
{availableStxBalance && (
<Suspense fallback={<></>}>
<AccountBalanceCaption availableBalance={availableStxBalance} />
</Suspense>
)}
</Stack>
</Stack>
{isLoading && <Spinner width={4} height={4} {...loadingProps} />}
Expand Down Expand Up @@ -154,10 +162,9 @@ export const Accounts = memo(() => {
style={{ height: '68px' }}
itemContent={(index, account) => (
<AccountItem
key={index}
account={account}
isLoading={selectedAccount === index}
onSelectAccount={index => signIntoAccount(index)}
onSelectAccount={signIntoAccount}
/>
)}
/>
Expand Down
7 changes: 5 additions & 2 deletions src/app/query/balance/balance.hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from '@app/store/accounts/account.hooks';
import { useGetAccountBalanceQuery, useGetAnchoredAccountBalanceQuery } from './balance.query';
import { accountBalanceStxKeys } from '@app/store/accounts/account.models';
import { useMemo } from 'react';

function initAmountsAsBigNumber(balances: AddressBalanceResponse): AccountBalanceResponseBigNumber {
const stxBigNumbers = Object.fromEntries(
Expand Down Expand Up @@ -42,8 +43,10 @@ export function useCurrentAccountUnanchoredBalances() {

export function useAddressAvailableStxBalance(address: string) {
const balances = useAddressBalances(address);
if (!balances) return new BigNumber(0);
return balances.stx.balance.minus(balances.stx.locked);
return useMemo(() => {
if (!balances) return new BigNumber(0);
return balances.stx.balance.minus(balances.stx.locked);
}, [balances]);
}

function useAddressAnchoredBalances(address: string) {
Expand Down
19 changes: 5 additions & 14 deletions src/app/query/bns/bns.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
import { useMemo } from 'react';
import { logger } from '@shared/logger';
import { useAccounts, useCurrentAccountStxAddressState } from '@app/store/accounts/account.hooks';
import { useGetBnsNamesOwnedByAddress, useGetBnsNamesOwnedByAddressList } from './bns.query';

export function useAllAccountNames() {
const accounts = useAccounts() ?? [];
const result = useGetBnsNamesOwnedByAddressList(accounts.map(a => a.address));
return accounts.map(({ address, index }) => ({
address,
index,
names: result[index].data?.names ?? [],
}));
}
import { useCurrentAccountStxAddressState } from '@app/store/accounts/account.hooks';
import { useGetBnsNamesOwnedByAddress } from './bns.query';

export function useCurrentAccountNames() {
const principal = useCurrentAccountStxAddressState();
if (!principal) logger.error('No principal defined');
const namesResponse = useGetBnsNamesOwnedByAddress(principal ?? '');
return namesResponse.data?.names ?? [];
return useMemo(() => namesResponse.data?.names ?? [], [namesResponse.data?.names]);
}

export function useGetAccountNamesByAddressQuery(address: string) {
const namesResponse = useGetBnsNamesOwnedByAddress(address);
return namesResponse.data?.names ?? [];
return useMemo(() => namesResponse.data?.names ?? [], [namesResponse.data?.names]);
}
14 changes: 1 addition & 13 deletions src/app/query/bns/bns.query.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useQueries, useQuery, UseQueryResult } from 'react-query';
import { useQuery } from 'react-query';

import { useApi, Api } from '@app/store/common/api-clients.hooks';
import { BnsNamesOwnByAddressResponse } from '@stacks/blockchain-api-client';

const staleTime = 15 * 60 * 1000; // 15 min

Expand All @@ -27,14 +26,3 @@ export function useGetBnsNamesOwnedByAddress(address: string) {
...bnsQueryOptions,
});
}

export function useGetBnsNamesOwnedByAddressList(addresses: string[]) {
const api = useApi();
return useQueries(
addresses.map(address => ({
queryKey: ['bns-names-by-address', address],
queryFn: getBnsNameFetcherFactory(api)(address),
...bnsQueryOptions,
}))
) as UseQueryResult<BnsNamesOwnByAddressResponse, Error>[];
}
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -14488,10 +14488,10 @@ react-is@^16.13.1, react-is@^16.7.0:
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==

react-query@3.34.7:
version "3.34.7"
resolved "https://registry.yarnpkg.com/react-query/-/react-query-3.34.7.tgz#e3d71318f510ea354794cd188b351bb57f577cb9"
integrity sha512-Q8+H2DgpoZdGUpwW2Z9WAbSrIE+yOdZiCUokHjlniOOmlcsfqNLgvHF5i7rtuCmlw3hv5OAhtpS7e97/DvgpWw==
react-query@3.34.12:
version "3.34.12"
resolved "https://registry.yarnpkg.com/react-query/-/react-query-3.34.12.tgz#dcaaf7b629f0868aae8afef9fb7692f6ea7643bf"
integrity sha512-flDdudQVH4CqE+kNYYYyo4g2Yjek3H/36G3b9bK5oe26jD5gFnx+PPwnq0gayq5z2dcSfr2z4+drvuyeZ3A5QQ==
dependencies:
"@babel/runtime" "^7.5.5"
broadcast-channel "^3.4.1"
Expand Down

0 comments on commit e60d527

Please sign in to comment.