| [81cdf2d] | 1 | // contexts/AuthContext.jsx
|
|---|
| 2 | import { createContext, useContext, useState, useEffect } from "react";
|
|---|
| 3 |
|
|---|
| 4 | const AuthContext = createContext();
|
|---|
| 5 |
|
|---|
| 6 | export const useAuth = () => {
|
|---|
| 7 | const context = useContext(AuthContext);
|
|---|
| 8 | if (!context) {
|
|---|
| 9 | throw new Error("useAuth must be used within AuthProvider");
|
|---|
| 10 | }
|
|---|
| 11 | return context;
|
|---|
| 12 | };
|
|---|
| 13 |
|
|---|
| 14 | export const AuthProvider = ({ children }) => {
|
|---|
| 15 | const [walletAddress, setWalletAddress] = useState(null);
|
|---|
| 16 | const [loading, setLoading] = useState(true);
|
|---|
| 17 | const [user, setUser] = useState(null);
|
|---|
| 18 |
|
|---|
| 19 | const fetchSavedWallet = async () => {
|
|---|
| 20 | try {
|
|---|
| 21 | const response = await fetch("http://localhost:8080/api/auth/me", {
|
|---|
| 22 | credentials: "include",
|
|---|
| 23 | });
|
|---|
| 24 |
|
|---|
| 25 | if (response.status === 403 || response.status === 401) {
|
|---|
| 26 | setWalletAddress(null);
|
|---|
| 27 | setUser(null);
|
|---|
| 28 | setLoading(false);
|
|---|
| 29 | return;
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | if (!response.ok) {
|
|---|
| 33 | throw new Error(`HTTP ${response.status}`);
|
|---|
| 34 | }
|
|---|
| 35 |
|
|---|
| 36 | const data = await response.json();
|
|---|
| 37 | console.log("Fetched user data:", data);
|
|---|
| 38 |
|
|---|
| 39 | setUser(data);
|
|---|
| 40 |
|
|---|
| 41 | const wallet = data.saved_wallet || data.metamuskAdresa || null;
|
|---|
| 42 | setWalletAddress(wallet);
|
|---|
| 43 | console.log("Wallet address set to:", wallet);
|
|---|
| 44 | } catch (err) {
|
|---|
| 45 | console.log("Error fetching saved wallet:", err.message);
|
|---|
| 46 | setWalletAddress(null);
|
|---|
| 47 | setUser(null);
|
|---|
| 48 | } finally {
|
|---|
| 49 | setLoading(false);
|
|---|
| 50 | }
|
|---|
| 51 | };
|
|---|
| 52 |
|
|---|
| 53 | const setBackendWalletAddress = (address) => {
|
|---|
| 54 | console.log("Setting wallet address to:", address);
|
|---|
| 55 | setWalletAddress(address);
|
|---|
| 56 | };
|
|---|
| 57 |
|
|---|
| 58 | useEffect(() => {
|
|---|
| 59 | fetchSavedWallet();
|
|---|
| 60 | }, []);
|
|---|
| 61 |
|
|---|
| 62 | return (
|
|---|
| 63 | <AuthContext.Provider
|
|---|
| 64 | value={{
|
|---|
| 65 | walletAddress,
|
|---|
| 66 | setBackendWalletAddress,
|
|---|
| 67 | fetchSavedWallet,
|
|---|
| 68 | loading,
|
|---|
| 69 | user,
|
|---|
| 70 | }}
|
|---|
| 71 | >
|
|---|
| 72 | {children}
|
|---|
| 73 | </AuthContext.Provider>
|
|---|
| 74 | );
|
|---|
| 75 | };
|
|---|