File size: 1,207 Bytes
90f0c0b
 
 
 
c1209d2
 
 
 
90f0c0b
 
 
 
 
 
 
c1209d2
 
90f0c0b
c1209d2
 
 
 
 
 
 
 
 
 
 
90f0c0b
 
c1209d2
90f0c0b
 
 
 
 
 
 
 
 
c1209d2
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
import React, { createContext, useContext, useState } from "react";

interface AuthContextType {
  isAuthenticated: boolean;
  // 1. Added username to the context type
  username: string;
  // 2. Updated login signature to accept the username string
  login: (name: string) => void;
  logout: () => void;
}

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

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  // 3. New state to hold the logged-in user's name
  const [username, setUsername] = useState('Guest');

  // 4. Updated login function to accept and set the username
  const login = (name: string) => {
    setUsername(name);
    setIsAuthenticated(true);
  };

  const logout = () => {
    // Reset state on logout
    setIsAuthenticated(false);
    setUsername('Guest');
  };

  return (
    <AuthContext.Provider value={{ isAuthenticated, 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;
};