UNPKG

1.26 kBTypeScriptView Raw
1import type {
2 NavigationAction,
3 NavigationState,
4 Router,
5} from '@react-navigation/routers';
6import * as React from 'react';
7
8import NavigationBuilderContext from './NavigationBuilderContext';
9
10type Options<Action extends NavigationAction> = {
11 router: Router<NavigationState, Action>;
12 getState: () => NavigationState;
13 setState: (state: NavigationState) => void;
14 key?: string;
15};
16
17/**
18 * Hook to handle focus actions for a route.
19 * Focus action needs to be treated specially, coz when a nested route is focused,
20 * the parent navigators also needs to be focused.
21 */
22export default function useOnRouteFocus<Action extends NavigationAction>({
23 router,
24 getState,
25 key: sourceRouteKey,
26 setState,
27}: Options<Action>) {
28 const { onRouteFocus: onRouteFocusParent } = React.useContext(
29 NavigationBuilderContext
30 );
31
32 return React.useCallback(
33 (key: string) => {
34 const state = getState();
35 const result = router.getStateForRouteFocus(state, key);
36
37 if (result !== state) {
38 setState(result);
39 }
40
41 if (onRouteFocusParent !== undefined && sourceRouteKey !== undefined) {
42 onRouteFocusParent(sourceRouteKey);
43 }
44 },
45 [getState, onRouteFocusParent, router, setState, sourceRouteKey]
46 );
47}