main
import type { MeResponse } from '@/shared/api'
import { useEffect, useState } from 'react'
import { AuthError } from '@/shared/api'
import { t } from '@/shared/i18n'
import { useTask } from '@/shared/lib'
import { fetchSession, logoutSession } from '../api/session'
export function useSession({
onUnauthenticated,
onLoggedOut,
}: {
onUnauthenticated: () => void
onLoggedOut?: () => void
}) {
const [user, setUser] = useState<MeResponse | null>(null)
const [loading, setLoading] = useState(true)
const task = useTask()
useEffect(() => {
const controller = new AbortController()
void fetchSession(controller.signal)
.then(setUser)
.catch((error) => {
if (controller.signal.aborted) return
if (error instanceof AuthError && error.code === 'unauthenticated') onUnauthenticated()
else task.setNotice({ kind: 'error', text: error instanceof Error ? error.message : t('account.unavailable') })
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [])
async function logout() {
await task.run(async (signal) => {
await logoutSession(signal)
onLoggedOut?.()
})
}
return { user, loading, task, logout }
}