about summary refs log tree commit diff
path: root/src/lib/hooks/useFollowDid.ts
blob: 223adb04754a92a45698928ecdbe0d0c0020fd01 (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 React from 'react'

import {useStores} from 'state/index'
import {FollowState} from 'state/models/cache/my-follows'

export function useFollowDid({did}: {did: string}) {
  const store = useStores()
  const state = store.me.follows.getFollowState(did)

  return {
    state,
    following: state === FollowState.Following,
    toggle: React.useCallback(async () => {
      if (state === FollowState.Following) {
        try {
          await store.agent.deleteFollow(store.me.follows.getFollowUri(did))
          store.me.follows.removeFollow(did)
          return {
            state: FollowState.NotFollowing,
            following: false,
          }
        } catch (e: any) {
          store.log.error('Failed to delete follow', e)
          throw e
        }
      } else if (state === FollowState.NotFollowing) {
        try {
          const res = await store.agent.follow(did)
          store.me.follows.addFollow(did, res.uri)
          return {
            state: FollowState.Following,
            following: true,
          }
        } catch (e: any) {
          store.log.error('Failed to create follow', e)
          throw e
        }
      }

      return {
        state: FollowState.Unknown,
        following: false,
      }
    }, [store, did, state]),
  }
}