From 026db3ba4c685a37fcba36b7dcf188d871fae288 Mon Sep 17 00:00:00 2001 From: hoangvu12 Date: Thu, 23 Nov 2023 03:55:50 +0700 Subject: [PATCH] feat: double back to exit the app --- src/hooks/use-double-exit.ts | 38 ++++++++++++++++++++++++++++++++++++ src/screens/anime/screen.tsx | 2 ++ 2 files changed, 40 insertions(+) create mode 100644 src/hooks/use-double-exit.ts diff --git a/src/hooks/use-double-exit.ts b/src/hooks/use-double-exit.ts new file mode 100644 index 0000000..a43b463 --- /dev/null +++ b/src/hooks/use-double-exit.ts @@ -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; diff --git a/src/screens/anime/screen.tsx b/src/screens/anime/screen.tsx index 143ea7c..9effae3 100644 --- a/src/screens/anime/screen.tsx +++ b/src/screens/anime/screen.tsx @@ -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, @@ -21,6 +22,7 @@ import WatchedList from './components/watched-list'; export const AnimeHomeScreen = () => { useModuleLinking(); + useDoubleExit(); const navigation = useNavigation();