import React, { useState, useEffect } from "react"; import { apiFetch } from "../utils/apiFetch"; interface UserInfo { connected: boolean; username: string | null; } interface CountResponse { name: string; count: number; } const Counter: React.FC = () => { const [userInfo, setUserInfo] = useState(null); const [count, setCount] = useState(0); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [incrementing, setIncrementing] = useState(false); useEffect(() => { const fetchUserInfo = async () => { try { setLoading(true); const response = await apiFetch("/api/user"); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data: UserInfo = await response.json(); setUserInfo(data); setError(null); // If user is logged in, fetch their count if (data.connected) { await fetchUserCount(); } } catch (err) { setError( err instanceof Error ? err.message : "Failed to fetch user info", ); setUserInfo(null); } finally { setLoading(false); } }; fetchUserInfo(); }, []); const fetchUserCount = async () => { try { const response = await apiFetch("/api/user/count"); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data: CountResponse = await response.json(); setCount(data.count); } catch (err) { console.error("Failed to fetch user count:", err); setCount(0); } }; const handleIncrement = async () => { if (!userInfo?.connected) { setError("You must be logged in to increment the counter"); return; } try { setIncrementing(true); setError(null); const response = await apiFetch("/api/user/count/increment", { method: "POST", }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data: CountResponse = await response.json(); setCount(data.count); } catch (err) { setError( err instanceof Error ? err.message : "Failed to increment counter", ); } finally { setIncrementing(false); } }; // Loading state if (loading) { return (
Loading...
); } // Not logged in state if (!userInfo?.connected) { return (

Please log in to use the counter

); } return (
{error && (

{error}

)}

Logged in as: {userInfo.username || "User"}

); }; export default Counter;