Skip to content

Commit

Permalink
feat: double back to exit the app
Browse files Browse the repository at this point in the history
  • Loading branch information
hoangvu12 committed Nov 22, 2023
1 parent 061489f commit 026db3b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/hooks/use-double-exit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { useNavigation } from '@react-navigation/native';
import { useEffect, useRef } from 'react';
import { BackHandler, ToastAndroid } from 'react-native';

const useDoubleExit = () => {
const backCount = useRef(0);

const navigation = useNavigation();

useEffect(() => {
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
() => {
if (navigation.canGoBack()) return;

backCount.current += 1;

if (backCount.current === 1) {
ToastAndroid.show(
'Press back again to exit the app',
ToastAndroid.SHORT
);

setTimeout(() => {
backCount.current = 0;
}, 2000);
} else if (backCount.current === 2) {
BackHandler.exitApp();
}

return true;
}
);
return () => backHandler.remove();
}, [navigation]);
};

export default useDoubleExit;
2 changes: 2 additions & 0 deletions src/screens/anime/screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useNavigation } from '@react-navigation/native';
import * as React from 'react';
import { ScrollView } from 'react-native';

import useDoubleExit from '@/hooks/use-double-exit';
import useModuleLinking from '@/hooks/use-module-linking';
import {
Button,
Expand All @@ -21,6 +22,7 @@ import WatchedList from './components/watched-list';

export const AnimeHomeScreen = () => {
useModuleLinking();
useDoubleExit();

const navigation = useNavigation();

Expand Down

0 comments on commit 026db3b

Please sign in to comment.