49 lines
1.1 KiB
TypeScript
49 lines
1.1 KiB
TypeScript
import { useState, useEffect } from 'react'
|
|
import { nostrConnectService } from '@/lib/nostrconnect'
|
|
import type { NostrConnectState } from '@/types/nostr'
|
|
|
|
export function useNostrConnect() {
|
|
const [state, setState] = useState<NostrConnectState>(nostrConnectService.getState())
|
|
const [loading, setLoading] = useState(false)
|
|
const [error, setError] = useState<string | null>(null)
|
|
|
|
useEffect(() => {
|
|
const unsubscribe = nostrConnectService.subscribe((newState) => {
|
|
setState(newState)
|
|
})
|
|
|
|
return unsubscribe
|
|
}, [])
|
|
|
|
const connect = async () => {
|
|
setLoading(true)
|
|
setError(null)
|
|
try {
|
|
await nostrConnectService.connect()
|
|
} catch (e) {
|
|
setError(e instanceof Error ? e.message : 'Connection failed')
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}
|
|
|
|
const disconnect = async () => {
|
|
setLoading(true)
|
|
try {
|
|
await nostrConnectService.disconnect()
|
|
} catch (e) {
|
|
setError(e instanceof Error ? e.message : 'Disconnection failed')
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}
|
|
|
|
return {
|
|
...state,
|
|
loading,
|
|
error,
|
|
connect,
|
|
disconnect,
|
|
}
|
|
}
|