({ children }: { children: React.ReactNode })
| 15 | const SupabaseContext = createContext<SupabaseContextType | null>(null) |
| 16 | |
| 17 | export function SupabaseProvider({ children }: { children: React.ReactNode }) { |
| 18 | const [user, setUser] = useState<User | null>(null) |
| 19 | const [loading, setLoading] = useState(true) |
| 20 | const [supabase, setSupabase] = useState<SupabaseClient | null>(null) |
| 21 | const router = useRouter() |
| 22 | |
| 23 | // Initialize Supabase client only on the client side |
| 24 | useEffect(() => { |
| 25 | try { |
| 26 | const client = createSupabaseClient() |
| 27 | setSupabase(client) |
| 28 | } catch (error) { |
| 29 | console.warn('Failed to create Supabase client:', error) |
| 30 | setLoading(false) |
| 31 | } |
| 32 | }, []) |
| 33 | |
| 34 | useEffect(() => { |
| 35 | if (!supabase) { |
| 36 | return |
| 37 | } |
| 38 | |
| 39 | let isMounted = true |
| 40 | |
| 41 | // Get initial session |
| 42 | supabase.auth.getSession().then(({ data: { session } }) => { |
| 43 | if (isMounted) { |
| 44 | setUser(session?.user ?? null) |
| 45 | setLoading(false) |
| 46 | } |
| 47 | }) |
| 48 | |
| 49 | // Listen for auth changes |
| 50 | const { data: { subscription } } = supabase.auth.onAuthStateChange(async (_event, session) => { |
| 51 | if (isMounted) { |
| 52 | setUser(session?.user ?? null) |
| 53 | |
| 54 | // Only set loading to false after the user state has been updated |
| 55 | if (_event === 'SIGNED_IN') { |
| 56 | // Small delay to ensure state propagation |
| 57 | setTimeout(() => { |
| 58 | if (isMounted) { |
| 59 | setLoading(false) |
| 60 | } |
| 61 | }, 100) |
| 62 | } else { |
| 63 | setLoading(false) |
| 64 | } |
| 65 | |
| 66 | // If user logs out, redirect to login |
| 67 | if (!session && _event === 'SIGNED_OUT') { |
| 68 | router.push('/') |
| 69 | } |
| 70 | } |
| 71 | }) |
| 72 | |
| 73 | return () => { |
| 74 | isMounted = false |
nothing calls this directly
no test coverage detected