added cashu context to prevent repeated invocation

This commit is contained in:
lemonknowsall committed 2025-10-06 20:47:01 -07:00
1 parent 669a911d59
commit 565305a592
3 files changed
+110 -8

No files matched your search

+74 -8
View File
@@ -87,17 +87,74 @@ When Cashu wallet is available and has sufficient balance:
## Required Dependencies
Ensure these hooks are available in your app:
**CRITICAL**: The `useCashu` hook MUST be wrapped in a Context Provider to avoid infinite loops!
### Setup CashuContext (Required!)
Create `src/contexts/CashuContext.tsx`:
```tsx
// Required for Cashu integration
import { useCashu } from '@/hooks/useCashu';
import { createContext, useContext, ReactNode } from 'react';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu';
// Required for traditional Lightning zaps
import { useWallet } from '@/hooks/useWallet';
import { useZaps } from '@/hooks/useZaps';
const CashuContext = createContext<UseCashuReturn | null>(null);
export function CashuProvider({ children }: { children: ReactNode }) {
const cashu = useCashuHook();
return (
<CashuContext.Provider value={cashu}>
{children}
</CashuContext.Provider>
);
}
export function useCashu(): UseCashuReturn {
const context = useContext(CashuContext);
if (!context) {
throw new Error('useCashu must be used within a CashuProvider');
}
return context;
}
```
### Wrap Your App
Add `CashuProvider` to your App.tsx:
```tsx
import { CashuProvider } from '@/contexts/CashuContext';
export function App() {
return (
<SomeProvider>
<CashuProvider>
{/* Your app */}
</CashuProvider>
</SomeProvider>
);
}
```
### Import from Context
**Always** import from the context, not the hook:
```tsx
// ✅ CORRECT
import { useCashu } from '@/contexts/CashuContext';
// ❌ WRONG - Will cause infinite loops!
import { useCashu } from '@/hooks/useCashu';
```
This ensures all components share the same Cashu wallet instance, preventing:
- Multiple wallet initializations
- Infinite refresh loops
- Performance issues
## Architecture Overview
**IMPORTANT**: The Cashu integration uses a **two-component architecture**:
@@ -276,7 +333,14 @@ data-testid="zap-modal"
### 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.
**Root Cause #1 (MOST COMMON)**: Multiple components are calling `useCashu()` directly from the hook instead of from the Context Provider. This creates multiple wallet instances that all try to initialize and refresh balances.
**Solution**: Ensure you:
1. Created `CashuContext.tsx` as shown in the Required Dependencies section
2. Wrapped your app with `<CashuProvider>`
3. Import `useCashu` from `@/contexts/CashuContext` in ALL components (not from `@/hooks/useCashu`)
**Root Cause #2**: 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
@@ -315,9 +379,11 @@ useEffect(() => {
## Integration Checklist
- [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies)
- [ ] **CRITICAL**: Wrap app with `<CashuProvider>` in App.tsx
- [ ] **CRITICAL**: Import `useCashu` from `@/contexts/CashuContext` in ALL components
- [ ] Import unified `ZapButton` component
- [ ] Create dedicated route/page for `CashuWallet` (don't embed in content feeds)
- [ ] Ensure `useCashu` hook is available
- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR
- [ ] Verify mobile responsiveness
- [ ] Test error handling scenarios
+25
View File
@@ -0,0 +1,25 @@
import { createContext, useContext, ReactNode } from 'react';
import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu';
const CashuContext = createContext<UseCashuReturn | null>(null);
export function CashuProvider({ children }: { children: ReactNode }) {
const cashu = useCashuHook();
return (
<CashuContext.Provider value={cashu}>
{children}
</CashuContext.Provider>
);
}
export function useCashu(): UseCashuReturn {
const context = useContext(CashuContext);
if (!context) {
throw new Error('useCashu must be used within a CashuProvider');
}
return context;
}
+11
View File
@@ -132,17 +132,26 @@ export function useCashu(): UseCashuReturn {
// Utility operations - defined first so they can be used in other callbacks
const lastRefreshTimeRef = useRef<number>(0);
const isRefreshingRef = useRef<boolean>(false);
const REFRESH_THROTTLE_MS = 500; // Prevent refreshing more than once every 500ms
const refreshBalances = useCallback(async () => {
if (!managerRef.current) return;
// Prevent concurrent calls
if (isRefreshingRef.current) {
console.log('⏭️ refreshBalances: Skipping (already in progress)');
return;
}
// Throttle rapid successive calls
const now = Date.now();
if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) {
console.log('⏭️ refreshBalances: Skipping (throttled)');
return;
}
isRefreshingRef.current = true;
lastRefreshTimeRef.current = now;
try {
@@ -166,6 +175,8 @@ export function useCashu(): UseCashuReturn {
});
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
} finally {
isRefreshingRef.current = false;
}
}, []);