All files / src/contexts AuthContext.tsx

80.64% Statements 25/31
80% Branches 4/5
100% Functions 0/0
85.18% Lines 23/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 61 62 63 64                                6x   30x     30x 30x 30x   30x   14x   3x 3x   14x 16x   30x 3x 3x 3x 16x   30x       16x     30x 30x     30x         143x   143x        
import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  type ReactNode,
} from "react";
 
interface AuthContextType {
  isAuthenticated: boolean;
  token: string | null;
  login: (token: string) => void;
  logout: () => void;
  initializing: boolean;
}
 
const AuthContext = createContext<AuthContextType | undefined>(undefined);
 
export const AuthProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [token, setToken] = useState<string | null>(null);
  const [initializing, setInitializing] = useState(true);
 
  useEffect(() => {
    // Check for existing token on app load
    const savedToken = localStorage.getItem("authToken");
    if (savedToken) {
      setToken(savedToken);
      setIsAuthenticated(true);
    }
    setInitializing(false); // <-- auth is fully loaded
  }, []);
 
  const login = (newToken: string) => {
    setToken(newToken);
    setIsAuthenticated(true);
    localStorage.setItem("authToken", newToken);
  };
 
  const logout = () => {
    setToken(null);
    setIsAuthenticated(false);
    localStorage.removeItem("authToken");
  };
 
  return (
    <AuthContext.Provider
      value={{ isAuthenticated, token, login, logout, initializing }}
    >
      {children}
    </AuthContext.Provider>
  );
};
 
export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};