All files / apps/host/src/hooks useBlockNavigation.ts

93.75% Statements 15/16
75% Branches 3/4
100% Functions 7/7
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38          3x         5x 5x           5x 5x 2x 1x     5x       5x   1x   1x   1x        
import { useCallback, useEffect } from 'react';
import { BackHandler } from 'react-native';
 
import { NavigationProp, ParamListBase, useFocusEffect } from '@react-navigation/native';
 
export const useBlockBackNavigationWhileSubmitting = (
  navigation: NavigationProp<ParamListBase>,
  isSubmitting: boolean,
) => {
  // Disable swipe back
  useEffect(() => {
    navigation.setOptions({
      gestureEnabled: !isSubmitting,
    });
  }, [navigation, isSubmitting]);
 
  // Block ALL navigation back actions
  useEffect(() => {
    const unsubscribe = navigation.addListener('beforeRemove', e => {
      if (!isSubmitting) return;
      e.preventDefault();
    });
 
    return unsubscribe;
  }, [navigation, isSubmitting]);
 
  // Block Android hardware back
  useFocusEffect(
    useCallback(() => {
      Iif (!isSubmitting) return;
 
      const subscription = BackHandler.addEventListener('hardwareBackPress', () => true);
 
      return () => subscription.remove();
    }, [isSubmitting]),
  );
};