// contexts/AuthContext.jsx import { createContext, useContext, useState, useEffect } from "react"; const AuthContext = createContext(); export const useAuth = () => { const context = useContext(AuthContext); if (!context) { throw new Error("useAuth must be used within AuthProvider"); } return context; }; export const AuthProvider = ({ children }) => { const [walletAddress, setWalletAddress] = useState(null); const [loading, setLoading] = useState(true); const [user, setUser] = useState(null); const fetchSavedWallet = async () => { try { const response = await fetch("http://localhost:8080/api/auth/me", { credentials: "include", }); if (response.status === 403 || response.status === 401) { setWalletAddress(null); setUser(null); setLoading(false); return; } if (!response.ok) { throw new Error(`HTTP ${response.status}`); } const data = await response.json(); console.log("Fetched user data:", data); setUser(data); const wallet = data.saved_wallet || data.metamuskAdresa || null; setWalletAddress(wallet); console.log("Wallet address set to:", wallet); } catch (err) { console.log("Error fetching saved wallet:", err.message); setWalletAddress(null); setUser(null); } finally { setLoading(false); } }; const setBackendWalletAddress = (address) => { console.log("Setting wallet address to:", address); setWalletAddress(address); }; useEffect(() => { fetchSavedWallet(); }, []); return ( {children} ); };