about summary refs log tree commit diff
path: root/src/lib/hooks/useNavigationDeduped.ts
blob: dc18742c02d5c6d6b53131d75ef46a2f9484242d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {useMemo} from 'react'
import {useNavigation} from '@react-navigation/core'

import {useDedupe} from '#/lib/hooks/useDedupe'
import {type NavigationProp} from '#/lib/routes/types'

export type DebouncedNavigationProp = Pick<
  NavigationProp,
  | 'popToTop'
  | 'push'
  | 'navigate'
  | 'canGoBack'
  | 'replace'
  | 'dispatch'
  | 'goBack'
  | 'getState'
>

export function useNavigationDeduped() {
  const navigation = useNavigation<NavigationProp>()
  const dedupe = useDedupe()

  return useMemo<DebouncedNavigationProp>(
    () => ({
      push: (...args: Parameters<typeof navigation.push>) => {
        dedupe(() => navigation.push(...args))
      },
      navigate: (...args: Parameters<typeof navigation.navigate>) => {
        dedupe(() => navigation.navigate(...args))
      },
      replace: (...args: Parameters<typeof navigation.replace>) => {
        dedupe(() => navigation.replace(...args))
      },
      dispatch: (...args: Parameters<typeof navigation.dispatch>) => {
        dedupe(() => navigation.dispatch(...args))
      },
      popToTop: () => {
        dedupe(() => navigation.popToTop())
      },
      goBack: () => {
        dedupe(() => navigation.goBack())
      },
      canGoBack: () => {
        return navigation.canGoBack()
      },
      getState: () => {
        return navigation.getState()
      },
    }),
    [dedupe, navigation],
  )
}