UNPKG

1.08 kBTypeScriptView Raw
1import * as React from 'react';
2
3import type { KeyedListenerMap } from './NavigationBuilderContext';
4
5/**
6 * Hook which lets child navigators add getters to be called for obtaining rehydrated state.
7 */
8export default function useKeyedChildListeners() {
9 const { current: keyedListeners } = React.useRef<{
10 [K in keyof KeyedListenerMap]: Record<
11 string,
12 KeyedListenerMap[K] | undefined
13 >;
14 }>(
15 Object.assign(Object.create(null), {
16 getState: {},
17 beforeRemove: {},
18 })
19 );
20
21 const addKeyedListener = React.useCallback(
22 <T extends keyof KeyedListenerMap>(
23 type: T,
24 key: string,
25 listener: KeyedListenerMap[T]
26 ) => {
27 // @ts-expect-error: according to ref stated above you can use `key` to index type
28 keyedListeners[type][key] = listener;
29
30 return () => {
31 // @ts-expect-error: according to ref stated above you can use `key` to index type
32 keyedListeners[type][key] = undefined;
33 };
34 },
35 [keyedListeners]
36 );
37
38 return {
39 keyedListeners,
40 addKeyedListener,
41 };
42}