SurfSense/surfsense_web/hooks/use-user.ts
DESKTOP-RTLN3BA\$punk b2a97b39ce refactor: centralize authentication handling
- Replaced direct localStorage token access with a centralized `getBearerToken` function across various components and hooks to improve code maintainability and security.
- Updated API calls to use `authenticatedFetch` for consistent authentication handling.
- Enhanced user experience by ensuring proper redirection to login when authentication fails.
- Cleaned up unused imports and improved overall code structure for better readability.
2025-12-02 01:24:09 -08:00

53 lines
1.2 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { authenticatedFetch } from "@/lib/auth-utils";
interface User {
id: string;
email: string;
is_active: boolean;
is_superuser: boolean;
is_verified: boolean;
pages_limit: number;
pages_used: number;
}
export function useUser() {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchUser = async () => {
try {
// Only run on client-side
if (typeof window === "undefined") return;
setLoading(true);
const response = await authenticatedFetch(
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/users/me`,
{ method: "GET" }
);
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.status}`);
}
const data = await response.json();
setUser(data);
setError(null);
} catch (err: any) {
setError(err.message || "Failed to fetch user");
console.error("Error fetching user:", err);
} finally {
setLoading(false);
}
};
fetchUser();
}, []);
return { user, loading, error };
}