mirror of
https://github.com/R0m1k3/Regisflow.git
synced 2026-10-13 18:26:54 +02:00
Force a page reload in `useAuth.ts` hook to ensure correct state after authentication. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 91318273-c764-4fd4-be04-bdc12c38af32 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/0715008c-7244-40f4-befc-26c014852236/dc9123b6-1916-42e7-8155-5dd0740be619.jpg
72 lines
1.9 KiB
TypeScript
72 lines
1.9 KiB
TypeScript
import { useState, useEffect } from "react";
|
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import { apiRequest } from "@/lib/queryClient";
|
|
import type { User, LoginData } from "@shared/schema";
|
|
|
|
export function useAuth() {
|
|
const queryClient = useQueryClient();
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
const checkAuth = async () => {
|
|
try {
|
|
const response = await fetch('/api/auth/me', {
|
|
credentials: 'include',
|
|
});
|
|
|
|
if (response.ok) {
|
|
const userData = await response.json();
|
|
setUser(userData);
|
|
} else {
|
|
setUser(null);
|
|
}
|
|
} catch (error) {
|
|
setUser(null);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
checkAuth();
|
|
}, []);
|
|
|
|
const loginMutation = useMutation({
|
|
mutationFn: async (credentials: LoginData) => {
|
|
const response = await apiRequest('/api/auth/login', {
|
|
method: 'POST',
|
|
body: JSON.stringify(credentials)
|
|
});
|
|
const data = await response.json();
|
|
return data;
|
|
},
|
|
onSuccess: (data) => {
|
|
setUser(data.user);
|
|
queryClient.clear();
|
|
// Force a page reload to ensure proper state update
|
|
window.location.reload();
|
|
},
|
|
});
|
|
|
|
const logoutMutation = useMutation({
|
|
mutationFn: async () => {
|
|
await apiRequest('/api/auth/logout', { method: 'POST' });
|
|
},
|
|
onSuccess: () => {
|
|
setUser(null);
|
|
queryClient.clear();
|
|
// Force a page reload to ensure all state is cleared
|
|
window.location.reload();
|
|
},
|
|
});
|
|
|
|
return {
|
|
user,
|
|
isLoading,
|
|
isAuthenticated: !!user,
|
|
login: loginMutation.mutateAsync,
|
|
logout: logoutMutation.mutateAsync,
|
|
isLoggingIn: loginMutation.isPending,
|
|
isLoggingOut: logoutMutation.isPending,
|
|
};
|
|
} |