ultisuite-client/lib/api/use-auth-ready.ts
2026-05-25 13:52:40 +02:00

25 lines
782 B
TypeScript

"use client"
import { useEffect, useState } from "react"
import { useAuthStore } from "@/lib/api/auth-store"
/** Wait for auth persist hydrate before enabling API queries. */
export function useAuthReady() {
// Always false on first render so SSR and hydration markup match; zustand
// `hasHydrated()` can be true on the server (in-memory persist) before the
// client has read localStorage.
const [ready, setReady] = useState(false)
const authenticated = useAuthStore((s) => s.isAuthenticated())
useEffect(() => {
if (useAuthStore.persist.hasHydrated()) {
setReady(true)
return
}
const unsub = useAuthStore.persist.onFinishHydration(() => setReady(true))
return unsub
}, [])
return { ready, authenticated: ready && authenticated }
}