init
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
|
||||
import { getMe, logout, type User } from '../../lib/api';
|
||||
|
||||
import { AuthContext } from './AuthContextValue';
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
getMe()
|
||||
.then(setUser)
|
||||
.catch(() => setUser(null))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
async function signOut() {
|
||||
await logout().catch(() => undefined);
|
||||
setUser(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, setUser, signOut }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/* The hook lives in useAuth.ts so Fast Refresh only sees the provider here. */
|
||||
@@ -0,0 +1,12 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
import type { User } from '../../lib/api';
|
||||
|
||||
export interface AuthContextValue {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
setUser: (user: User | null) => void;
|
||||
signOut: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useContext } from 'react';
|
||||
|
||||
import { AuthContext } from './AuthContextValue';
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used inside AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user