Basic home, Login, and Auth in client
This commit is contained in:
46
client/src/contexts/AuthContext.jsx
Normal file
46
client/src/contexts/AuthContext.jsx
Normal file
@@ -0,0 +1,46 @@
|
||||
// src/contexts/AuthContext.jsx
|
||||
import { createContext, useContext, useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const AuthContext = createContext();
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('token');
|
||||
setIsAuthenticated(!!token);
|
||||
setIsLoading(false);
|
||||
}, []);
|
||||
|
||||
const login = async (username, password) => {
|
||||
try {
|
||||
const response = await axios.post(`${import.meta.env.VITE_API_URL}/api/auth/login`, {
|
||||
username,
|
||||
password
|
||||
});
|
||||
localStorage.setItem('token', response.data.token);
|
||||
setIsAuthenticated(true);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('token');
|
||||
setIsAuthenticated(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ isAuthenticated, isLoading, login, logout }}>
|
||||
{!isLoading && children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
return useContext(AuthContext);
|
||||
}
|
||||
Reference in New Issue
Block a user