about summary refs log tree commit diff
path: root/src/lib/hooks/useAccountSwitcher.ts
blob: b165fddb59dff34ff053f6886b5b5fccccef95ce (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
import {useCallback, useState} from 'react'
import {useStores} from 'state/index'
import {useAnalytics} from 'lib/analytics/analytics'
import {StackActions, useNavigation} from '@react-navigation/native'
import {NavigationProp} from 'lib/routes/types'
import {AccountData} from 'state/models/session'
import {reset as resetNavigation} from '../../Navigation'
import * as Toast from 'view/com/util/Toast'
import {useSetDrawerOpen} from '#/state/shell/drawer-open'
import {useModalControls} from '#/state/modals'

export function useAccountSwitcher(): [
  boolean,
  (v: boolean) => void,
  (acct: AccountData) => Promise<void>,
] {
  const {track} = useAnalytics()
  const store = useStores()
  const setDrawerOpen = useSetDrawerOpen()
  const {closeModal} = useModalControls()
  const [isSwitching, setIsSwitching] = useState(false)
  const navigation = useNavigation<NavigationProp>()

  const onPressSwitchAccount = useCallback(
    async (acct: AccountData) => {
      track('Settings:SwitchAccountButtonClicked')
      setIsSwitching(true)
      const success = await store.session.resumeSession(acct)
      setDrawerOpen(false)
      closeModal()
      store.shell.closeAllActiveElements()
      if (success) {
        resetNavigation()
        Toast.show(`Signed in as ${acct.displayName || acct.handle}`)
      } else {
        Toast.show('Sorry! We need you to enter your password.')
        navigation.navigate('HomeTab')
        navigation.dispatch(StackActions.popToTop())
        store.session.clear()
      }
    },
    [track, setIsSwitching, navigation, store, setDrawerOpen, closeModal],
  )

  return [isSwitching, setIsSwitching, onPressSwitchAccount]
}