source: frontend/web3-eDnevnik_Frontend/src/contexts/AuthContext.jsx

Last change on this file was 81cdf2d, checked in by Nikola Janev <nikolajanev57@…>, 9 days ago

initial commit

  • Property mode set to 100644
File size: 1.8 KB
RevLine 
[81cdf2d]1// contexts/AuthContext.jsx
2import { createContext, useContext, useState, useEffect } from "react";
3
4const AuthContext = createContext();
5
6export 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
14export 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};
Note: See TracBrowser for help on using the repository browser.