Merge pull request #6622 from BlueWallet/walletslistcallback

REF: WalletsList useCallback
This commit is contained in:
GLaDOS 2024-05-27 19:50:28 +00:00 committed by GitHub
commit e3c1240a77
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -151,19 +151,20 @@ const WalletsList: React.FC = () => {
walletsCount.current = wallets.length; walletsCount.current = wallets.length;
}, [wallets]); }, [wallets]);
const verifyBalance = () => { const verifyBalance = useCallback(() => {
if (getBalance() !== 0) { if (getBalance() !== 0) {
A(A.ENUM.GOT_NONZERO_BALANCE); A(A.ENUM.GOT_NONZERO_BALANCE);
} else { } else {
A(A.ENUM.GOT_ZERO_BALANCE); A(A.ENUM.GOT_ZERO_BALANCE);
} }
}; }, [getBalance]);
/** /**
* Forcefully fetches TXs and balance for ALL wallets. * Forcefully fetches TXs and balance for ALL wallets.
* Triggered manually by user on pull-to-refresh. * Triggered manually by user on pull-to-refresh.
*/ */
const refreshTransactions = async (showLoadingIndicator = true, showUpdateStatusIndicator = false) => { const refreshTransactions = useCallback(
async (showLoadingIndicator = true, showUpdateStatusIndicator = false) => {
if (isElectrumDisabled) { if (isElectrumDisabled) {
dispatch({ type: ActionTypes.SET_LOADING, payload: false }); dispatch({ type: ActionTypes.SET_LOADING, payload: false });
return; return;
@ -172,14 +173,17 @@ const WalletsList: React.FC = () => {
refreshAllWalletTransactions(undefined, showUpdateStatusIndicator).finally(() => { refreshAllWalletTransactions(undefined, showUpdateStatusIndicator).finally(() => {
dispatch({ type: ActionTypes.SET_LOADING, payload: false }); dispatch({ type: ActionTypes.SET_LOADING, payload: false });
}); });
}; },
[isElectrumDisabled, refreshAllWalletTransactions],
);
useEffect(() => { useEffect(() => {
refreshTransactions(false, true); refreshTransactions(false, true);
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // call refreshTransactions() only once, when screen mounts }, []);
const handleClick = (item?: TWallet) => { const handleClick = useCallback(
(item?: TWallet) => {
if (item?.getID) { if (item?.getID) {
const walletID = item.getID(); const walletID = item.getID();
navigate('WalletTransactions', { navigate('WalletTransactions', {
@ -189,31 +193,33 @@ const WalletsList: React.FC = () => {
} else { } else {
navigate('AddWalletRoot'); navigate('AddWalletRoot');
} }
}; },
[navigate],
);
const setIsLoading = (value: boolean) => { const setIsLoading = useCallback((value: boolean) => {
dispatch({ type: ActionTypes.SET_LOADING, payload: value }); dispatch({ type: ActionTypes.SET_LOADING, payload: value });
}; }, []);
const onSnapToItem = (e: { nativeEvent: { contentOffset: any } }) => { const onSnapToItem = useCallback(
(e: { nativeEvent: { contentOffset: any } }) => {
if (!isFocused) return; if (!isFocused) return;
const contentOffset = e.nativeEvent.contentOffset; const contentOffset = e.nativeEvent.contentOffset;
const index = Math.ceil(contentOffset.x / width); const index = Math.ceil(contentOffset.x / width);
if (currentWalletIndex.current !== index) { if (currentWalletIndex.current !== index) {
console.log('onSnapToItem', wallets.length === index ? 'NewWallet/Importing card' : index); console.debug('onSnapToItem', wallets.length === index ? 'NewWallet/Importing card' : index);
if (wallets[index] && (wallets[index].timeToRefreshBalance() || wallets[index].timeToRefreshTransaction())) { if (wallets[index] && (wallets[index].timeToRefreshBalance() || wallets[index].timeToRefreshTransaction())) {
console.log(wallets[index].getLabel(), 'thinks its time to refresh either balance or transactions. refetching both');
refreshAllWalletTransactions(index, false).finally(() => setIsLoading(false)); refreshAllWalletTransactions(index, false).finally(() => setIsLoading(false));
} }
currentWalletIndex.current = index; currentWalletIndex.current = index;
} else {
console.log('onSnapToItem did not change. Most likely momentum stopped at the same index it started.');
} }
}; },
[isFocused, refreshAllWalletTransactions, setIsLoading, wallets, width],
);
const renderListHeaderComponent = () => { const renderListHeaderComponent = useCallback(() => {
return ( return (
<View style={[styles.listHeaderBack, stylesHook.listHeaderBack]}> <View style={[styles.listHeaderBack, stylesHook.listHeaderBack]}>
<Text textBreakStrategy="simple" style={[styles.listHeaderText, stylesHook.listHeaderText]}> <Text textBreakStrategy="simple" style={[styles.listHeaderText, stylesHook.listHeaderText]}>
@ -221,28 +227,29 @@ const WalletsList: React.FC = () => {
</Text> </Text>
</View> </View>
); );
}; }, [stylesHook.listHeaderBack, stylesHook.listHeaderText]);
const handleLongPress = () => { const handleLongPress = useCallback(() => {
if (wallets.length > 1) { if (wallets.length > 1) {
navigate('ReorderWallets'); navigate('ReorderWallets');
} else { } else {
triggerHapticFeedback(HapticFeedbackTypes.NotificationError); triggerHapticFeedback(HapticFeedbackTypes.NotificationError);
} }
}; }, [navigate, wallets.length]);
const renderTransactionListsRow = (item: ExtendedTransaction) => { const renderTransactionListsRow = useCallback(
return ( (item: ExtendedTransaction) => (
<View style={styles.transaction}> <View style={styles.transaction}>
<TransactionListItem item={item} itemPriceUnit={item.walletPreferredBalanceUnit} walletID={item.walletID} /> <TransactionListItem item={item} itemPriceUnit={item.walletPreferredBalanceUnit} walletID={item.walletID} />
</View> </View>
),
[],
); );
};
const renderWalletsCarousel = () => { const renderWalletsCarousel = useCallback(() => {
return ( return (
<WalletsCarousel <WalletsCarousel
// @ts-ignore: Convert to TS later // @ts-ignore: Fix later
data={wallets.concat(false)} data={wallets.concat(false)}
extraData={[wallets]} extraData={[wallets]}
onPress={handleClick} onPress={handleClick}
@ -254,9 +261,10 @@ const WalletsList: React.FC = () => {
scrollEnabled={isFocused} scrollEnabled={isFocused}
/> />
); );
}; }, [handleClick, handleLongPress, isFocused, onSnapToItem, wallets]);
const renderSectionItem = (item: { section: any; item: ExtendedTransaction }) => { const renderSectionItem = useCallback(
(item: { section: any; item: ExtendedTransaction }) => {
switch (item.section.key) { switch (item.section.key) {
case WalletsListSections.CAROUSEL: case WalletsListSections.CAROUSEL:
return isLargeScreen ? null : renderWalletsCarousel(); return isLargeScreen ? null : renderWalletsCarousel();
@ -265,9 +273,12 @@ const WalletsList: React.FC = () => {
default: default:
return null; return null;
} }
}; },
[isLargeScreen, renderTransactionListsRow, renderWalletsCarousel],
);
const renderSectionHeader = (section: { section: { key: any } }) => { const renderSectionHeader = useCallback(
(section: { section: { key: any } }) => {
switch (section.section.key) { switch (section.section.key) {
case WalletsListSections.CAROUSEL: case WalletsListSections.CAROUSEL:
return isLargeScreen ? null : <Header leftText={loc.wallets.list_title} onNewWalletPress={() => navigate('AddWalletRoot')} />; return isLargeScreen ? null : <Header leftText={loc.wallets.list_title} onNewWalletPress={() => navigate('AddWalletRoot')} />;
@ -276,9 +287,12 @@ const WalletsList: React.FC = () => {
default: default:
return null; return null;
} }
}; },
[isLargeScreen, navigate, renderListHeaderComponent],
);
const renderSectionFooter = (section: { section: { key: any } }) => { const renderSectionFooter = useCallback(
(section: { section: { key: any } }) => {
switch (section.section.key) { switch (section.section.key) {
case WalletsListSections.TRANSACTIONS: case WalletsListSections.TRANSACTIONS:
if (dataSource.length === 0 && !isLoading) { if (dataSource.length === 0 && !isLoading) {
@ -294,9 +308,11 @@ const WalletsList: React.FC = () => {
default: default:
return null; return null;
} }
}; },
[dataSource.length, isLoading],
);
const renderScanButton = () => { const renderScanButton = useCallback(() => {
if (wallets.length > 0) { if (wallets.length > 0) {
return ( return (
<FContainer ref={walletActionButtonsRef.current}> <FContainer ref={walletActionButtonsRef.current}>
@ -311,30 +327,35 @@ const WalletsList: React.FC = () => {
} else { } else {
return null; return null;
} }
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [scanImage, wallets.length]);
const sectionListKeyExtractor = (item: any, index: any) => { const sectionListKeyExtractor = (item: any, index: any) => {
return `${item}${index}}`; return `${item}${index}}`;
}; };
const onScanButtonPressed = () => { const onScanButtonPressed = useCallback(() => {
scanQrHelper(routeName).then(onBarScanned); scanQrHelper(routeName).then(onBarScanned);
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onBarScanned = (value: any) => { const onBarScanned = useCallback(
(value: any) => {
if (!value) return; if (!value) return;
DeeplinkSchemaMatch.navigationRouteFor({ url: value }, completionValue => { DeeplinkSchemaMatch.navigationRouteFor({ url: value }, completionValue => {
triggerHapticFeedback(HapticFeedbackTypes.NotificationSuccess); triggerHapticFeedback(HapticFeedbackTypes.NotificationSuccess);
// @ts-ignore: Fix later // @ts-ignore: for now
navigate(...completionValue); navigate(...completionValue);
}); });
}; },
[navigate],
);
const copyFromClipboard = async () => { const copyFromClipboard = useCallback(async () => {
onBarScanned(await BlueClipboard().getClipboardContent()); onBarScanned(await BlueClipboard().getClipboardContent());
}; }, [onBarScanned]);
const sendButtonLongPress = async () => { const sendButtonLongPress = useCallback(async () => {
const isClipboardEmpty = (await BlueClipboard().getClipboardContent()).trim().length === 0; const isClipboardEmpty = (await BlueClipboard().getClipboardContent()).trim().length === 0;
const options = [loc._.cancel, loc.wallets.list_long_choose, loc.wallets.list_long_scan]; const options = [loc._.cancel, loc.wallets.list_long_choose, loc.wallets.list_long_scan];
@ -358,7 +379,6 @@ const WalletsList: React.FC = () => {
fs.showImagePickerAndReadImage() fs.showImagePickerAndReadImage()
.then(onBarScanned) .then(onBarScanned)
.catch(error => { .catch(error => {
console.log(error);
triggerHapticFeedback(HapticFeedbackTypes.NotificationError); triggerHapticFeedback(HapticFeedbackTypes.NotificationError);
presentAlert({ title: loc.errors.error, message: error.message }); presentAlert({ title: loc.errors.error, message: error.message });
}); });
@ -373,12 +393,13 @@ const WalletsList: React.FC = () => {
break; break;
} }
}); });
}; }, [copyFromClipboard, onBarScanned, routeName]);
const onRefresh = () => { const onRefresh = useCallback(() => {
refreshTransactions(true, false); refreshTransactions(true, false);
};
// Optimized for Mac option doesn't like RN Refresh component. Menu Elements now handles it for macOS // Optimized for Mac option doesn't like RN Refresh component. Menu Elements now handles it for macOS
}, [refreshTransactions]);
const refreshProps = isDesktop || isElectrumDisabled ? {} : { refreshing: isLoading, onRefresh }; const refreshProps = isDesktop || isElectrumDisabled ? {} : { refreshing: isLoading, onRefresh };
const sections: SectionData[] = [ const sections: SectionData[] = [
@ -401,6 +422,9 @@ const WalletsList: React.FC = () => {
contentInset={styles.scrollContent} contentInset={styles.scrollContent}
renderSectionFooter={renderSectionFooter} renderSectionFooter={renderSectionFooter}
sections={sections} sections={sections}
windowSize={21}
maxToRenderPerBatch={10}
updateCellsBatchingPeriod={50}
/> />
{renderScanButton()} {renderScanButton()}
</View> </View>