WellNuo/app/_layout.tsx
Sergei 69c999729f Fix BLE connections not disconnecting on logout
Implemented proper BLE cleanup mechanism on user logout:

**Root Cause:**
- BLE cleanup callback was being set but reference could become stale
- No explicit cleanup call in profile logout handler
- Callback stability issues due to re-renders

**Changes:**
1. app/_layout.tsx:
   - Use useRef pattern to maintain stable callback reference
   - Set callback once with ref that always points to current cleanupBLE
   - Cleanup callback on unmount to prevent memory leaks

2. app/(tabs)/profile/index.tsx:
   - Add explicit cleanupBLE() call in logout handler
   - Import useBLE hook to access cleanup function
   - Ensure cleanup happens before logout completes

3. services/api.ts:
   - Update setOnLogoutBLECleanupCallback signature to accept null
   - Allows proper cleanup of callback on unmount

4. jest.setup.js:
   - Add AsyncStorage mock to prevent test failures

5. Tests:
   - Add comprehensive BLE cleanup tests
   - Test callback pattern and stability
   - Test logout flow with BLE cleanup
   - Test error handling during cleanup

**Result:**
BLE connections now properly disconnect when user logs out,
preventing stale connections and potential resource leaks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-29 12:19:46 -08:00

123 lines
4.0 KiB
TypeScript

import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { Stack, router, useRootNavigationState, useSegments } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import { useEffect, useRef } from 'react';
import 'react-native-reanimated';
import { StripeProvider } from '@stripe/stripe-react-native';
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
import { ToastProvider } from '@/components/ui/Toast';
import { AuthProvider, useAuth } from '@/contexts/AuthContext';
import { BeneficiaryProvider } from '@/contexts/BeneficiaryContext';
import { BLEProvider, useBLE } from '@/contexts/BLEContext';
import { useColorScheme } from '@/hooks/use-color-scheme';
import { setOnLogoutBLECleanupCallback } from '@/services/api';
// Stripe publishable key (test mode) - must match backend STRIPE_PUBLISHABLE_KEY
const STRIPE_PUBLISHABLE_KEY = 'pk_test_51P3kdqP0gvUw6M9C7ixPQHqbPcvga4G5kAYx1h6QXQAt1psbrC2rrmOojW0fTeQzaxD1Q9RKS3zZ23MCvjjZpWLi00eCFWRHMk';
// Prevent auto-hide, ignore errors if splash not available
SplashScreen.preventAutoHideAsync().catch(() => {});
// Track if splash screen was hidden to prevent double-hiding
let splashHidden = false;
function RootLayoutNav() {
const colorScheme = useColorScheme();
const { isAuthenticated, isInitializing } = useAuth();
const { cleanupBLE } = useBLE();
const segments = useSegments();
const navigationState = useRootNavigationState();
// Track if initial redirect was done
const hasInitialRedirect = useRef(false);
// Set up BLE cleanup callback for logout
// Use ref to ensure callback is always current and stable
const cleanupBLERef = useRef(cleanupBLE);
useEffect(() => {
cleanupBLERef.current = cleanupBLE;
}, [cleanupBLE]);
useEffect(() => {
// Set callback that calls the current ref (always up-to-date)
setOnLogoutBLECleanupCallback(() => cleanupBLERef.current());
// Cleanup: remove callback on unmount
return () => {
setOnLogoutBLECleanupCallback(null);
};
}, []); // Empty deps - set once, callback uses ref
useEffect(() => {
// Wait for navigation to be ready
if (!navigationState?.key) {
return;
}
// Wait for INITIAL auth check to complete
if (isInitializing) {
return;
}
// Hide splash screen safely (only once)
if (!splashHidden) {
splashHidden = true;
SplashScreen.hideAsync().catch(() => {});
}
const inAuthGroup = segments[0] === '(auth)';
// INITIAL REDIRECT (only once after app starts):
// - If not authenticated and not in auth → go to login
if (!hasInitialRedirect.current) {
hasInitialRedirect.current = true;
if (!isAuthenticated && !inAuthGroup) {
router.replace('/(auth)/login');
return;
}
}
// If not authenticated, do NOTHING - let the auth screens handle their own navigation
}, [isAuthenticated, isInitializing, navigationState?.key]);
// IMPORTANT: isLoading NOT in deps - we don't want to react to loading state changes
// segments also not in deps - we don't want to react to navigation changes
if (isInitializing) {
return <LoadingSpinner fullScreen message="Loading..." />;
}
return (
<ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="(auth)" />
<Stack.Screen name="(tabs)" />
<Stack.Screen name="modal" options={{ presentation: 'modal', title: 'Modal' }} />
</Stack>
<StatusBar style="auto" />
</ThemeProvider>
);
}
export default function RootLayout() {
return (
<StripeProvider
publishableKey={STRIPE_PUBLISHABLE_KEY}
merchantIdentifier="merchant.com.wellnuo.app"
>
<AuthProvider>
<BeneficiaryProvider>
<BLEProvider>
<ToastProvider>
<RootLayoutNav />
</ToastProvider>
</BLEProvider>
</BeneficiaryProvider>
</AuthProvider>
</StripeProvider>
);
}