about summary refs log tree commit diff
path: root/src/view/com/util/UserInfoText.tsx
blob: 536eef9e4a70ecbf5b93336284e8cab6395f40e5 (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
53
54
import React, {useState, useEffect} from 'react'
import * as AppBskyGetProfile from '../../../third-party/api/src/types/app/bsky/getProfile'
import {StyleProp, Text, TextStyle} from 'react-native'
import {useStores} from '../../../state'

export function UserInfoText({
  did,
  attr,
  loading,
  failed,
  prefix,
  style,
}: {
  did: string
  attr?: keyof AppBskyGetProfile.OutputSchema
  loading?: string
  failed?: string
  prefix?: string
  style?: StyleProp<TextStyle>
}) {
  attr = attr || 'name'
  loading = loading || '...'
  failed = failed || 'user'

  const store = useStores()
  const [profile, setProfile] = useState<
    undefined | AppBskyGetProfile.OutputSchema
  >(undefined)
  const [didFail, setFailed] = useState<boolean>(false)

  useEffect(() => {
    let aborted = false
    // TODO use caching to reduce loads
    store.api.app.bsky.getProfile({user: did}).then(
      v => {
        if (aborted) return
        setProfile(v.data)
      },
      _err => {
        if (aborted) return
        setFailed(true)
      },
    )
    return () => {
      aborted = true
    }
  }, [did, store.api.app.bsky])

  return (
    <Text style={style}>
      {didFail ? failed : profile ? `${prefix}${profile[attr]}` : loading}
    </Text>
  )
}