Files
ncuetalk_front/src/context/AuthContext.jsx
dsyoon d56d136522 init
2025-08-18 09:40:54 +09:00

53 lines
1.6 KiB
JavaScript

import React, { createContext, useContext, useEffect, useState } from 'react';
const AuthContext = createContext();
export function AuthProvider({ children }) {
const [user, setUser] = useState(null); // { user_id, email }
const [loading, setLoading] = useState(true);
useEffect(() => {
try {
const saved = JSON.parse(localStorage.getItem('auth_user') || 'null');
if (saved && saved.user_id) setUser(saved);
} catch {}
setLoading(false);
}, []);
const login = async (email, password) => {
const res = await fetch('http://localhost:8010/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ email, password }),
});
if (!res.ok) {
// 서버가 에러 메시지를 JSON 으로 보낼 수도 있으므로 파싱 시도
let msg = '로그인 실패';
try { msg = (await res.json())?.detail || msg; } catch { /* ignore */ }
throw new Error(msg);
}
const data = await res.json(); // { user_id, email }
setUser(data);
try { localStorage.setItem('auth_user', JSON.stringify(data)); } catch {}
return data;
};
const logout = async () => {
try {
await fetch('http://localhost:8010/auth/logout', { method: 'POST', credentials: 'include' });
} catch {}
setUser(null);
try { localStorage.removeItem('auth_user'); } catch {}
};
const value = { user, loading, login, logout };
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
return useContext(AuthContext);
}