85 lines
2.7 KiB
TypeScript
85 lines
2.7 KiB
TypeScript
import React, { useState, useEffect } from 'react';
|
|
import { LandingPage } from './LandingPage.js';
|
|
import { TourDetailPage } from './TourDetailPage.js';
|
|
import { ExploreMap } from './ExploreMap.js';
|
|
import { SignupPage } from './SignupPage.js';
|
|
|
|
const App = () => {
|
|
type View = 'landing' | 'explore' | 'detail' | 'signup';
|
|
const [view, setView] = useState<View>('landing');
|
|
const [isInitialSetup, setIsInitialSetup] = useState(false);
|
|
const [user, setUser] = useState<any>(null);
|
|
const [isUserLoaded, setIsUserLoaded] = useState(false); // Trạng thái để biết user đã được load từ localStorage chưa
|
|
|
|
useEffect(() => {
|
|
// Tự động xác định địa chỉ IP của Backend dựa trên hostname hiện tại
|
|
const API_BASE = `http://${window.location.hostname}:3001`;
|
|
|
|
// Khôi phục phiên đăng nhập từ localStorage
|
|
const savedUser = localStorage.getItem('user');
|
|
if (savedUser) {
|
|
const parsedUser = JSON.parse(savedUser);
|
|
setUser(parsedUser);
|
|
}
|
|
setIsUserLoaded(true); // Đánh dấu user đã được load
|
|
|
|
// Kiểm tra xem hệ thống đã được cài đặt chưa
|
|
fetch(`${API_BASE}/api/v1/auth/status`)
|
|
.then(res => res.ok ? res.json() : Promise.reject())
|
|
.then(data => setIsInitialSetup(!!data.isInitialSetup))
|
|
.catch(() => setIsInitialSetup(false));
|
|
}, []); // Chạy một lần khi component mount
|
|
|
|
// Effect để xử lý chuyển hướng nếu user đã đăng nhập và đang ở trang landing
|
|
useEffect(() => {
|
|
if (isUserLoaded && user && view === 'landing') {
|
|
setView('explore');
|
|
}
|
|
}, [isUserLoaded, user, view]);
|
|
|
|
const handleLoginSuccess = (userData: any) => {
|
|
setUser(userData);
|
|
};
|
|
|
|
const handleLogout = () => {
|
|
localStorage.removeItem('user');
|
|
localStorage.removeItem('token');
|
|
setUser(null);
|
|
setView('landing');
|
|
};
|
|
|
|
return (
|
|
<div className="app-container">
|
|
{view === 'landing' && (
|
|
<LandingPage
|
|
isInitialSetup={isInitialSetup}
|
|
onContinue={() => setView('explore')}
|
|
onGoToSignup={() => setView('signup')}
|
|
onGoToMap={() => setView('explore')}
|
|
onLoginSuccess={handleLoginSuccess}
|
|
/>
|
|
)}
|
|
|
|
{view === 'signup' && (
|
|
<SignupPage
|
|
onBack={() => setView('landing')}
|
|
onSuccess={() => setView('landing')}
|
|
/>
|
|
)}
|
|
|
|
{view === 'explore' && (
|
|
<ExploreMap
|
|
onBack={() => setView('landing')}
|
|
onLogout={user ? handleLogout : undefined}
|
|
user={user}
|
|
/>
|
|
)}
|
|
|
|
{view === 'detail' && (
|
|
<TourDetailPage />
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default App; |