Initial MUH app implementation
This commit is contained in:
58
frontend/src/lib/session.tsx
Normal file
58
frontend/src/lib/session.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type PropsWithChildren,
|
||||
} from "react";
|
||||
import { USER_STORAGE_KEY } from "./storage";
|
||||
import type { UserOption } from "./types";
|
||||
|
||||
interface SessionContextValue {
|
||||
user: UserOption | null;
|
||||
setUser: (user: UserOption | null) => void;
|
||||
}
|
||||
|
||||
const SessionContext = createContext<SessionContextValue>({
|
||||
user: null,
|
||||
setUser: () => undefined,
|
||||
});
|
||||
|
||||
function loadStoredUser(): UserOption | null {
|
||||
const raw = window.localStorage.getItem(USER_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(raw) as UserOption;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function SessionProvider({ children }: PropsWithChildren) {
|
||||
const [user, setUserState] = useState<UserOption | null>(() => loadStoredUser());
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
window.localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(user));
|
||||
return;
|
||||
}
|
||||
window.localStorage.removeItem(USER_STORAGE_KEY);
|
||||
}, [user]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
user,
|
||||
setUser: setUserState,
|
||||
}),
|
||||
[user],
|
||||
);
|
||||
|
||||
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
|
||||
}
|
||||
|
||||
export function useSession() {
|
||||
return useContext(SessionContext);
|
||||
}
|
||||
Reference in New Issue
Block a user