balance refresh infinite loop example

This commit is contained in:
lemonknowsall committed 2025-10-06 20:22:08 -07:00
1 parent 39796c293a
commit 669a911d59
2 files changed
+116 -8

No files matched your search

+45
View File
@@ -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
<Button onClick={() => refreshBalances()}>
Refresh
</Button>
```
**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.
+71 -8
View File
@@ -131,15 +131,39 @@ export function useCashu(): UseCashuReturn {
const repositoriesRef = useRef<unknown>(null);
// Utility operations - defined first so they can be used in other callbacks
const lastRefreshTimeRef = useRef<number>(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<CashuBalance> } }).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<CashuBalance> } }).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);
}