Files
pagodera/lib/hooks/use-session-query.ts
2025-11-11 03:08:36 -03:00

65 lines
1.4 KiB
TypeScript

"use client";
import { useQuery } from "@tanstack/react-query";
export interface SessionUser {
userId: number;
username: string;
email: string;
characterName: string | null;
subscriptionTier: {
id: number | null;
name: string | null;
slug: string | null;
level: number | null;
} | null;
}
interface SessionResponse {
success: boolean;
authenticated: boolean;
user?: SessionUser;
}
/**
* Hook para gerenciar sessão do usuário com React Query
* Atualiza automaticamente a cada 30 segundos
*/
export function useSession() {
const { data, isLoading, refetch } = useQuery<SessionResponse>({
queryKey: ["session"],
queryFn: async () => {
const response = await fetch("/api/auth/session", {
method: "GET",
credentials: "include",
});
return response.json();
},
staleTime: 1000 * 30, // 30 segundos
refetchInterval: 1000 * 30, // Refetch a cada 30 segundos
refetchOnWindowFocus: true,
refetchOnReconnect: true,
});
const logout = async () => {
try {
await fetch("/api/auth/session", {
method: "DELETE",
credentials: "include",
});
// Invalidar cache e recarregar
window.location.href = "/";
} catch (error) {
console.error("Erro ao fazer logout:", error);
}
};
return {
user: data?.user || null,
isLoading,
isAuthenticated: data?.authenticated || false,
logout,
refreshSession: refetch,
};
}