VERY MESSY FRONTEND NOTHING IS WORKING AAAAAAAAAAA
This commit is contained in:
parent
8b4de658fe
commit
a412ea8af7
31 changed files with 6694 additions and 265 deletions
63
frontend/src/context/AuthContext.tsx
Normal file
63
frontend/src/context/AuthContext.tsx
Normal file
|
@ -0,0 +1,63 @@
|
|||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { User } from '../types/api';
|
||||
import * as api from '../api/client';
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
register: (email: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
const userData = JSON.parse(localStorage.getItem('user') || 'null');
|
||||
setUser(userData);
|
||||
}
|
||||
setIsLoading(false);
|
||||
}, []);
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const response = await api.login(email, password);
|
||||
const { token, user } = response;
|
||||
localStorage.setItem('token', token);
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
setUser(user);
|
||||
};
|
||||
|
||||
const register = async (email: string, password: string) => {
|
||||
const response = await api.register(email, password);
|
||||
const { token, user } = response;
|
||||
localStorage.setItem('token', token);
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
setUser(user);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, login, register, logout, isLoading }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue