File size: 1,701 Bytes
acceac1
90f0c0b
 
 
35d0ce7
c1209d2
acceac1
90f0c0b
 
 
 
 
 
 
acceac1
35d0ce7
90f0c0b
acceac1
35d0ce7
acceac1
 
35d0ce7
acceac1
 
 
 
35d0ce7
 
 
acceac1
 
 
 
 
c1209d2
 
 
 
 
acceac1
 
c1209d2
acceac1
c1209d2
90f0c0b
 
35d0ce7
 
 
90f0c0b
 
 
 
 
 
 
 
 
acceac1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import React, { createContext, useContext, useState, useEffect } from "react";

interface AuthContextType {
  isAuthenticated: boolean;
  isLoading: boolean; // <--- Added: Tracks if we are still checking local storage
  username: string;
  login: (name: string, token: string) => void;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [username, setUsername] = useState("Guest");
  const [isLoading, setIsLoading] = useState(true); // <--- Start loading immediately

  useEffect(() => {
    // Check local storage on initial load
    const token = localStorage.getItem("token");
    const storedUser = localStorage.getItem("username");

    if (token) {
      setIsAuthenticated(true);
      if (storedUser) setUsername(storedUser);
    }

    // Done checking, stop loading
    setIsLoading(false);
  }, []);

  const login = (name: string, token: string) => {
    localStorage.setItem("token", token);
    localStorage.setItem("username", name);
    setUsername(name);
    setIsAuthenticated(true);
  };

  const logout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("username");
    setIsAuthenticated(false);
    setUsername("Guest");
  };

  return (
    <AuthContext.Provider
      value={{ isAuthenticated, isLoading, username, login, logout }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error("useAuth must be inside AuthProvider");
  return ctx;
};