Skip to content

Commit

Permalink
add customBackHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
adamgrzybowski committed Apr 10, 2024
1 parent 2d78c11 commit b57d456
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/pages/Search/SearchPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import ScreenWrapper from '@components/ScreenWrapper';
import type {CentralPaneNavigatorParamList} from '@libs/Navigation/types';
import type SCREENS from '@src/SCREENS';
import SearchResults from './SearchResults';
import useCustomBackHandler from './useCustomBackHandler';

type SearchPageProps = StackScreenProps<CentralPaneNavigatorParamList, typeof SCREENS.SEARCH>;
type SearchPageProps = StackScreenProps<CentralPaneNavigatorParamList, typeof SCREENS.SEARCH.CENTRAL_PANE>;

function SearchPage({route}: SearchPageProps) {
useCustomBackHandler();

return (
<ScreenWrapper testID="testPage">
<SearchResults filter={route.params.query} />
Expand Down
32 changes: 32 additions & 0 deletions src/pages/Search/useCustomBackHandler/index.android.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {StackActions, useFocusEffect} from '@react-navigation/native';
import {useCallback} from 'react';
import {BackHandler} from 'react-native';
import getTopmostCentralPaneRoute from '@libs/Navigation/getTopmostCentralPaneRoute';
import navigationRef from '@libs/Navigation/navigationRef';
import type {RootStackParamList, State} from '@libs/Navigation/types';
import NAVIGATORS from '@src/NAVIGATORS';
import SCREENS from '@src/SCREENS';

function useCustomBackHandler() {
useFocusEffect(
useCallback(() => {
const onBackPress = () => {
const rootState = navigationRef.getRootState();

const bottomTabRoute = rootState.routes.find((route) => route.name === NAVIGATORS.BOTTOM_TAB_NAVIGATOR);
const centralPaneRouteAfterPop = getTopmostCentralPaneRoute({routes: [rootState.routes.at(-2)]} as State<RootStackParamList>);

if (bottomTabRoute && bottomTabRoute.state && (!centralPaneRouteAfterPop || centralPaneRouteAfterPop.name !== SCREENS.SEARCH.CENTRAL_PANE)) {
navigationRef.dispatch({...StackActions.pop(), target: bottomTabRoute.state.key});
}
return false;
};

const subscription = BackHandler.addEventListener('hardwareBackPress', onBackPress);

return () => subscription.remove();
}, []),
);
}

export default useCustomBackHandler;
3 changes: 3 additions & 0 deletions src/pages/Search/useCustomBackHandler/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function useCustomBackHandler() {}

export default useCustomBackHandler;

0 comments on commit b57d456

Please sign in to comment.