55 lines
1.4 KiB
TypeScript

import { useState, useEffect } from 'react'
import { nostrAuthService } from '@/lib/nostrAuth'
import type { NostrConnectState } from '@/types/nostr'
export function useNostrAuth() {
const [state, setState] = useState<NostrConnectState>(nostrAuthService.getState())
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [accountExists, setAccountExists] = useState<boolean | null>(null)
useEffect(() => {
const unsubscribe = nostrAuthService.subscribe((newState) => {
setState(newState)
})
// Check if account exists on mount
nostrAuthService.accountExists().then(setAccountExists).catch(() => setAccountExists(false))
return unsubscribe
}, [])
const connect = async () => {
setLoading(true)
setError(null)
try {
await nostrAuthService.connect()
} catch (e) {
setError(e instanceof Error ? e.message : 'Connection failed')
} finally {
setLoading(false)
}
}
const disconnect = async () => {
setLoading(true)
try {
nostrAuthService.disconnect()
} catch (e) {
setError(e instanceof Error ? e.message : 'Disconnection failed')
} finally {
setLoading(false)
}
}
return {
...state,
loading,
error,
connect,
disconnect,
accountExists,
isUnlocked: nostrAuthService.isUnlocked(),
}
}