File size: 1,232 Bytes
38d787b
 
1185ec1
38d787b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useTransition } from "react"

import { UserInfo } from "@/types/general"

import { useStore } from "./useStore"
import { useLocalStorage } from "usehooks-ts"
import { localStorageKeys } from "./localStorageKeys"
import { defaultSettings } from "./defaultSettings"
import { getCurrentUser } from "../server/actions/users"

export function useCurrentUser(): UserInfo | undefined {
  const [_pending, startTransition] = useTransition()

  const currentUser = useStore(s => s.currentUser)
  const setCurrentUser = useStore(s => s.setCurrentUser)

  const [huggingfaceApiKey] = useLocalStorage<string>(
    localStorageKeys.huggingfaceApiKey,
    defaultSettings.huggingfaceApiKey
  )
  useEffect(() => {
    startTransition(async () => {

      // no key
      if (!huggingfaceApiKey) {
        setCurrentUser(undefined)
        return
      }

      // already logged-in
      if (currentUser?.id) {
        return
      }
      try {

        const user = await getCurrentUser(huggingfaceApiKey)

        setCurrentUser(user)
      } catch (err) {
        console.error("failed to log in:", err)
        setCurrentUser(undefined)
      }
    })
  
  }, [huggingfaceApiKey, currentUser?.id])

  return currentUser
}