Files
gitlab-instance-0a899031_di…/app/lib/useAuthAndVip.ts
2026-03-12 03:54:22 -05:00

46 lines
1.3 KiB
TypeScript

"use client";
import { useState, useEffect, useCallback } from "react";
export interface AuthAndVipState {
user: { id: string; email: string } | null;
vip: boolean;
loading: boolean;
refetch: () => Promise<{ user: { id: string; email: string } | null; vip: boolean }>;
}
export function useAuthAndVip(): AuthAndVipState {
const [user, setUser] = useState<{ id: string; email: string } | null>(null);
const [vip, setVip] = useState(false);
const [loading, setLoading] = useState(true);
const refetch = useCallback(async (): Promise<{ user: typeof user; vip: boolean }> => {
setLoading(true);
try {
const [meRes, vipRes] = await Promise.all([
fetch("/api/auth/me", { credentials: "include" }),
fetch("/api/vip/check", { credentials: "include" }),
]);
const meData = await meRes.json();
const vipData = await vipRes.json();
const newUser = meData?.user ?? null;
const newVip = vipData?.vip === true;
setUser(newUser);
setVip(newVip);
return { user: newUser, vip: newVip };
} catch {
setUser(null);
setVip(false);
return { user: null, vip: false };
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refetch();
}, [refetch]);
return { user, vip, loading, refetch };
}