From 669a911d595f4c74a63a528fc229c25a7708cc6e Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Mon, 6 Oct 2025 20:22:08 -0700 Subject: [PATCH] balance refresh infinite loop example --- docs/CASHU_ZAP_INTEGRATION.md | 45 ++++++++++++++++++++ src/hooks/useCashu.ts | 79 +++++++++++++++++++++++++++++++---- 2 files changed, 116 insertions(+), 8 deletions(-) diff --git a/docs/CASHU_ZAP_INTEGRATION.md b/docs/CASHU_ZAP_INTEGRATION.md index 4bb1d1f..9ab0623 100644 --- a/docs/CASHU_ZAP_INTEGRATION.md +++ b/docs/CASHU_ZAP_INTEGRATION.md @@ -250,6 +250,10 @@ data-testid="zap-modal" 5. **Trust the intelligence**: The component handles payment method selection automatically 6. **Test all scenarios**: Ensure Cashu, WebLN, NWC, and manual zaps all work 7. **Follow the architecture**: Use `ZapButton` for content integration, `CashuWallet` for wallet management +8. **Avoid Infinite Loops**: The `useCashu` hook includes throttling and deep comparison to prevent infinite refresh loops. Do NOT: + - Call `refreshBalances()` in `useEffect` that depends on `balances` + - Create circular dependencies between state updates and effects + - Override the built-in throttling mechanisms ## Troubleshooting @@ -269,6 +273,46 @@ data-testid="zap-modal" - Ensure zap endpoint is accessible - Test manual QR code fallback +### Infinite Loop: `refreshBalances` Repeatedly Called +If you see continuous console logs like `🔄 refreshBalances: Getting balances from wallet...`, the issue is likely: + +**Root Cause**: A `useEffect` that depends on `balances` is triggering `refreshBalances()`, creating a circular dependency. + +**Built-in Protections**: The `useCashu` hook includes: +- **Throttling**: Prevents calls more than once every 500ms +- **Deep Comparison**: Only updates state if balance values actually changed +- **Stable References**: Returns the same object reference when values are unchanged + +**Common Mistakes to Avoid**: +```tsx +// ❌ INCORRECT: Creates infinite loop +useEffect(() => { + refreshBalances(); +}, [balances, refreshBalances]); + +// ❌ INCORRECT: Calls refreshBalances on every balance change +useEffect(() => { + if (balances) { + refreshBalances(); + } +}, [balances]); + +// ✅ CORRECT: Only call on mount or user action +useEffect(() => { + refreshBalances(); // Called once on mount +}, []); // Empty dependency array + +// ✅ CORRECT: Call on user action + +``` + +**If Issue Persists**: Check your implementation for: +1. Effects that call `refreshBalances` and depend on `balances` +2. Custom hooks that wrap `useCashu` and create circular dependencies +3. Component re-renders that trigger unintended effect runs + ## Integration Checklist - [ ] Import unified `ZapButton` component @@ -278,5 +322,6 @@ data-testid="zap-modal" - [ ] Verify mobile responsiveness - [ ] Test error handling scenarios - [ ] Verify component separation (wallet management vs content integration) +- [ ] Check console for infinite `refreshBalances` loops (should see throttling logs if working correctly) This unified integration provides a seamless, intelligent zap experience that automatically selects the best available payment method while leveraging the benefits of both Cashu tokens and Lightning payments. diff --git a/src/hooks/useCashu.ts b/src/hooks/useCashu.ts index 06962a3..a8e75c0 100644 --- a/src/hooks/useCashu.ts +++ b/src/hooks/useCashu.ts @@ -131,15 +131,39 @@ export function useCashu(): UseCashuReturn { const repositoriesRef = useRef(null); // Utility operations - defined first so they can be used in other callbacks + const lastRefreshTimeRef = useRef(0); + const REFRESH_THROTTLE_MS = 500; // Prevent refreshing more than once every 500ms + const refreshBalances = useCallback(async () => { if (!managerRef.current) return; + // Throttle rapid successive calls + const now = Date.now(); + if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) { + console.log('⏭️ refreshBalances: Skipping (throttled)'); + return; + } + lastRefreshTimeRef.current = now; + try { console.log('🔄 refreshBalances: Getting balances from wallet...'); const newBalances = await (managerRef.current as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); - setBalances(newBalances); - console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); + + // Only update state if balances actually changed (deep comparison) + setBalances(prevBalances => { + const hasChanged = + Object.keys(newBalances).length !== Object.keys(prevBalances).length || + Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); + + if (hasChanged) { + console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); + return newBalances; + } else { + console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); + return prevBalances; + } + }); } catch (err) { console.error('❌ refreshBalances: Failed to refresh balances:', err); } @@ -208,8 +232,21 @@ export function useCashu(): UseCashuReturn { console.log('🔄 refreshBalances: Getting balances from wallet...'); const newBalances = await (managerRef.current as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); - setBalances(newBalances); - console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); + + // Only update state if balances actually changed (deep comparison) + setBalances(prevBalances => { + const hasChanged = + Object.keys(newBalances).length !== Object.keys(prevBalances).length || + Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); + + if (hasChanged) { + console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); + return newBalances; + } else { + console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); + return prevBalances; + } + }); } catch (err) { console.error('❌ refreshBalances: Failed to refresh balances:', err); } @@ -265,8 +302,21 @@ export function useCashu(): UseCashuReturn { console.log('🔄 refreshBalances: Getting balances from wallet...'); const newBalances = await manager.wallet.getBalances(); console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); - setBalances(newBalances); - console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); + + // Only update state if balances actually changed (deep comparison) + setBalances(prevBalances => { + const hasChanged = + Object.keys(newBalances).length !== Object.keys(prevBalances).length || + Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); + + if (hasChanged) { + console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); + return newBalances; + } else { + console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); + return prevBalances; + } + }); } catch (err) { console.error('❌ refreshBalances: Failed to refresh balances:', err); } @@ -323,8 +373,21 @@ export function useCashu(): UseCashuReturn { console.log('🔄 refreshBalances: Getting balances from wallet...'); const newBalances = await manager.wallet.getBalances(); console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); - setBalances(newBalances); - console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); + + // Only update state if balances actually changed (deep comparison) + setBalances(prevBalances => { + const hasChanged = + Object.keys(newBalances).length !== Object.keys(prevBalances).length || + Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); + + if (hasChanged) { + console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); + return newBalances; + } else { + console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); + return prevBalances; + } + }); } catch (err) { console.error('❌ refreshBalances: Failed to refresh balances:', err); }