about summary refs log tree commit diff
path: root/src/lib/hooks/useAccountSwitcher.ts
blob: 8385367358977a6be003ad9b72e15715ffb24002 (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
import {useCallback} from 'react'

import {useAnalytics} from '#/lib/analytics/analytics'
import {useStores} from '#/state/index'
import {useSetDrawerOpen} from '#/state/shell/drawer-open'
import {useModalControls} from '#/state/modals'
import {useSessionApi, SessionAccount} from '#/state/session'
import * as Toast from '#/view/com/util/Toast'

export function useAccountSwitcher() {
  const {track} = useAnalytics()
  const store = useStores()
  const setDrawerOpen = useSetDrawerOpen()
  const {closeModal} = useModalControls()
  const {selectAccount, clearCurrentAccount} = useSessionApi()

  const onPressSwitchAccount = useCallback(
    async (acct: SessionAccount) => {
      track('Settings:SwitchAccountButtonClicked')

      try {
        await selectAccount(acct)
        setDrawerOpen(false)
        closeModal()
        store.shell.closeAllActiveElements()
        Toast.show(`Signed in as ${acct.handle}`)
      } catch (e) {
        Toast.show('Sorry! We need you to enter your password.')
        clearCurrentAccount() // back user out to login
      }
    },
    [
      track,
      store,
      setDrawerOpen,
      closeModal,
      clearCurrentAccount,
      selectAccount,
    ],
  )

  return {onPressSwitchAccount}
}