import React, { useRef, useState, useEffect, useContext } from 'react'; import { Link, useNavigate, useLocation } from 'react-router-dom'; import { ProfileCtx } from '../App.js'; function SignIn({ setIsAuthenticated, setUser }) { const navigate = useNavigate(); const { setFinancialProfile, setScenario } = useContext(ProfileCtx); const usernameRef = useRef(''); const passwordRef = useRef(''); const [error, setError] = useState(''); const [showSessionExpiredMsg, setShowSessionExpiredMsg] = useState(false); const location = useLocation(); const apiUrl = process.env.REACT_APP_API_URL; useEffect(() => { // Check if the URL query param has ?session=expired const query = new URLSearchParams(location.search); if (query.get('session') === 'expired') { setShowSessionExpiredMsg(true); } }, [location.search]); const handleSignIn = async (event) => { event.preventDefault(); setError(''); // 0️⃣ clear everything that belongs to the *previous* user localStorage.removeItem('careerSuggestionsCache'); localStorage.removeItem('lastSelectedCareerProfileId'); localStorage.removeItem('aiClickCount'); localStorage.removeItem('aiClickDate'); localStorage.removeItem('aiRecommendations'); localStorage.removeItem('premiumOnboardingState'); localStorage.removeItem('financialProfile'); // if you cache it localStorage.removeItem('selectedScenario'); const username = usernameRef.current.value; const password = passwordRef.current.value; if (!username || !password) { setError('Please enter both username and password'); return; } try { const resp = await fetch(`${apiUrl}/signin`, { method : 'POST', headers: { 'Content-Type': 'application/json' }, body : JSON.stringify(username, password), }); const data = await resp.json(); // ← read ONCE if (!resp.ok) throw new Error(data.error || 'Failed to sign in'); /* ---------------- success path ---------------- */ const { token, id, user } = data; // fetch current user profile immediately const profileRes = await fetch('/api/user-profile', { headers: { Authorization: `Bearer ${token}` } }); const profile = await profileRes.json(); setFinancialProfile(profile); setScenario(null); // or fetch latest scenario separately /* purge any leftovers from prior session */ ['careerSuggestionsCache', 'lastSelectedCareerProfileId', 'aiClickCount', 'aiClickDate', 'aiRecommendations', 'premiumOnboardingState', 'financialProfile', 'selectedScenario' ].forEach(k => localStorage.removeItem(k)); /* store new session data */ localStorage.setItem('token', token); localStorage.setItem('id', id); setIsAuthenticated(true); setUser(user); navigate('/signin-landing'); } catch (err) { setError(err.message); } }; return (
{error}
)}Don’t have an account?{' '} Sign Up