refactor
This commit is contained in:
@@ -10,7 +10,8 @@
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.20.0"
|
||||
"react-router-dom": "^6.20.0",
|
||||
"react-hot-toast": "^2.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
|
||||
62
frontend/src/components/ErrorBoundary.jsx
Normal file
62
frontend/src/components/ErrorBoundary.jsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import React from 'react';
|
||||
|
||||
class ErrorBoundary extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error) {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error, errorInfo) {
|
||||
console.error('Error caught by boundary:', error, errorInfo);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<div style={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
padding: '2rem'
|
||||
}}>
|
||||
<div className="card" style={{ maxWidth: '500px', textAlign: 'center' }}>
|
||||
<h1 style={{ marginBottom: '1rem', color: 'var(--danger)' }}>Oops! Something went wrong</h1>
|
||||
<p style={{ marginBottom: '1.5rem', color: 'var(--text-muted)' }}>
|
||||
We're sorry, but something unexpected happened. Please refresh the page to try again.
|
||||
</p>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={() => window.location.href = '/'}
|
||||
>
|
||||
Go Home
|
||||
</button>
|
||||
{process.env.NODE_ENV === 'development' && this.state.error && (
|
||||
<details style={{ marginTop: '2rem', textAlign: 'left' }}>
|
||||
<summary style={{ cursor: 'pointer', color: 'var(--text-muted)' }}>Error Details</summary>
|
||||
<pre style={{
|
||||
marginTop: '1rem',
|
||||
padding: '1rem',
|
||||
background: 'var(--bg)',
|
||||
borderRadius: '0.5rem',
|
||||
overflow: 'auto',
|
||||
fontSize: '0.75rem'
|
||||
}}>
|
||||
{this.state.error.toString()}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export default ErrorBoundary;
|
||||
20
frontend/src/hooks/useClickOutside.js
Normal file
20
frontend/src/hooks/useClickOutside.js
Normal file
@@ -0,0 +1,20 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export function useClickOutside(ref, handler) {
|
||||
useEffect(() => {
|
||||
const listener = (event) => {
|
||||
if (!ref.current || ref.current.contains(event.target)) {
|
||||
return;
|
||||
}
|
||||
handler(event);
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', listener);
|
||||
document.addEventListener('touchstart', listener);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', listener);
|
||||
document.removeEventListener('touchstart', listener);
|
||||
};
|
||||
}, [ref, handler]);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter, Routes, Route, Navigate, Link } from 'react-router-dom';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import { AuthProvider, useAuth } from './AuthContext';
|
||||
import Login from './pages/Login';
|
||||
import Register from './pages/Register';
|
||||
@@ -9,6 +10,7 @@ import ChallengeDetail from './pages/ChallengeDetail';
|
||||
import Profile from './pages/Profile';
|
||||
import Friends from './pages/Friends';
|
||||
import Leaderboard from './pages/Leaderboard';
|
||||
import ErrorBoundary from './components/ErrorBoundary';
|
||||
import './App.css';
|
||||
|
||||
function ProtectedRoute({ children }) {
|
||||
@@ -50,21 +52,46 @@ function Header() {
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<Header />
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/challenges" element={<ProtectedRoute><ChallengeList /></ProtectedRoute>} />
|
||||
<Route path="/challenges/:id" element={<ProtectedRoute><ChallengeDetail /></ProtectedRoute>} />
|
||||
<Route path="/profile" element={<ProtectedRoute><Profile /></ProtectedRoute>} />
|
||||
<Route path="/friends" element={<ProtectedRoute><Friends /></ProtectedRoute>} />
|
||||
<Route path="/leaderboard" element={<ProtectedRoute><Leaderboard /></ProtectedRoute>} />
|
||||
<Route path="/" element={<Navigate to="/challenges" />} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
<ErrorBoundary>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<Toaster
|
||||
position="top-right"
|
||||
toastOptions={{
|
||||
duration: 3000,
|
||||
style: {
|
||||
background: '#1e293b',
|
||||
color: '#f1f5f9',
|
||||
border: '1px solid #334155',
|
||||
},
|
||||
success: {
|
||||
iconTheme: {
|
||||
primary: '#10b981',
|
||||
secondary: '#f1f5f9',
|
||||
},
|
||||
},
|
||||
error: {
|
||||
iconTheme: {
|
||||
primary: '#ef4444',
|
||||
secondary: '#f1f5f9',
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Header />
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/challenges" element={<ProtectedRoute><ChallengeList /></ProtectedRoute>} />
|
||||
<Route path="/challenges/:id" element={<ProtectedRoute><ChallengeDetail /></ProtectedRoute>} />
|
||||
<Route path="/profile" element={<ProtectedRoute><Profile /></ProtectedRoute>} />
|
||||
<Route path="/friends" element={<ProtectedRoute><Friends /></ProtectedRoute>} />
|
||||
<Route path="/leaderboard" element={<ProtectedRoute><Leaderboard /></ProtectedRoute>} />
|
||||
<Route path="/" element={<Navigate to="/challenges" />} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useAuth } from '../AuthContext';
|
||||
import api from '../api';
|
||||
import { useClickOutside } from '../hooks/useClickOutside';
|
||||
|
||||
export default function ChallengeDetail() {
|
||||
const { id } = useParams();
|
||||
@@ -15,6 +17,11 @@ export default function ChallengeDetail() {
|
||||
const [showInvite, setShowInvite] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchTimeout, setSearchTimeout] = useState(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [validating, setValidating] = useState(null);
|
||||
const searchRef = useRef(null);
|
||||
|
||||
useClickOutside(searchRef, () => setSearchResults([]));
|
||||
|
||||
useEffect(() => {
|
||||
loadChallenge();
|
||||
@@ -55,25 +62,33 @@ export default function ChallengeDetail() {
|
||||
e.preventDefault();
|
||||
if (!newPrediction.trim()) return;
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await api.createPrediction({
|
||||
challenge_id: id,
|
||||
content: newPrediction
|
||||
});
|
||||
toast.success('Prediction submitted!');
|
||||
setNewPrediction('');
|
||||
await loadPredictions();
|
||||
} catch (err) {
|
||||
alert('Failed to create prediction: ' + err.message);
|
||||
toast.error('Failed to create prediction: ' + err.message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleValidate = async (predictionId, status) => {
|
||||
setValidating(predictionId);
|
||||
try {
|
||||
await api.validatePrediction(predictionId, status);
|
||||
toast.success(status === 'validated' ? 'Prediction validated!' : 'Prediction invalidated');
|
||||
await loadPredictions();
|
||||
await loadLeaderboard();
|
||||
} catch (err) {
|
||||
alert('Failed to validate: ' + err.message);
|
||||
toast.error('Failed to validate: ' + err.message);
|
||||
} finally {
|
||||
setValidating(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -106,11 +121,11 @@ export default function ChallengeDetail() {
|
||||
const handleInvite = async (userId) => {
|
||||
try {
|
||||
await api.inviteToChallenge(id, { user_ids: [userId] });
|
||||
toast.success('Invitation sent!');
|
||||
setInviteQuery('');
|
||||
setSearchResults([]);
|
||||
alert('Invitation sent!');
|
||||
} catch (err) {
|
||||
alert('Failed to send invite: ' + err.message);
|
||||
toast.error('Failed to send invite: ' + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -154,7 +169,7 @@ export default function ChallengeDetail() {
|
||||
|
||||
{/* Invite Section */}
|
||||
{showInvite && (
|
||||
<div className="card" style={{ marginBottom: '2rem', position: 'relative' }}>
|
||||
<div className="card" style={{ marginBottom: '2rem', position: 'relative' }} ref={searchRef}>
|
||||
<h3 style={{ marginBottom: '1rem' }}>Invite Someone</h3>
|
||||
<input
|
||||
type="text"
|
||||
@@ -232,8 +247,8 @@ export default function ChallengeDetail() {
|
||||
onChange={(e) => setNewPrediction(e.target.value)}
|
||||
style={{ minHeight: '80px' }}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary" style={{ marginTop: '1rem' }}>
|
||||
Submit Prediction
|
||||
<button type="submit" className="btn btn-primary" style={{ marginTop: '1rem' }} disabled={submitting}>
|
||||
{submitting ? 'Submitting...' : 'Submit Prediction'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
@@ -261,14 +276,16 @@ export default function ChallengeDetail() {
|
||||
<button
|
||||
className="btn btn-success btn-sm"
|
||||
onClick={() => handleValidate(pred.id, 'validated')}
|
||||
disabled={validating === pred.id}
|
||||
>
|
||||
✓ Validate
|
||||
{validating === pred.id ? '...' : '✓ Validate'}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger btn-sm"
|
||||
onClick={() => handleValidate(pred.id, 'invalidated')}
|
||||
disabled={validating === pred.id}
|
||||
>
|
||||
✗ Invalidate
|
||||
{validating === pred.id ? '...' : '✗ Invalidate'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import api from '../api';
|
||||
import { useClickOutside } from '../hooks/useClickOutside';
|
||||
|
||||
export default function ChallengeList() {
|
||||
const [challenges, setChallenges] = useState([]);
|
||||
@@ -10,6 +12,10 @@ export default function ChallengeList() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [searchTimeout, setSearchTimeout] = useState(null);
|
||||
const [respondingTo, setRespondingTo] = useState(null);
|
||||
const searchRef = useRef(null);
|
||||
|
||||
useClickOutside(searchRef, () => setShowResults([]));
|
||||
|
||||
useEffect(() => {
|
||||
loadChallenges();
|
||||
@@ -31,11 +37,15 @@ export default function ChallengeList() {
|
||||
};
|
||||
|
||||
const handleRespondToInvite = async (challengeId, status) => {
|
||||
setRespondingTo(challengeId);
|
||||
try {
|
||||
await api.respondToChallenge(challengeId, status);
|
||||
toast.success(status === 'accepted' ? 'Challenge accepted!' : 'Challenge declined');
|
||||
await loadChallenges();
|
||||
} catch (err) {
|
||||
alert('Failed to respond: ' + err.message);
|
||||
toast.error('Failed to respond: ' + err.message);
|
||||
} finally {
|
||||
setRespondingTo(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -72,18 +82,19 @@ export default function ChallengeList() {
|
||||
? `https://image.tmdb.org/t/p/w500${show.poster_path}`
|
||||
: null;
|
||||
|
||||
const result = await api.createChallenge({
|
||||
await api.createChallenge({
|
||||
title: show.title,
|
||||
cover_image_url: coverImage,
|
||||
tmdb_id: show.id,
|
||||
media_type: show.media_type
|
||||
});
|
||||
|
||||
toast.success('Challenge created!');
|
||||
setSearchQuery('');
|
||||
setShowResults([]);
|
||||
await loadChallenges();
|
||||
} catch (err) {
|
||||
alert('Failed to create challenge: ' + err.message);
|
||||
toast.error('Failed to create challenge: ' + err.message);
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
@@ -124,14 +135,16 @@ export default function ChallengeList() {
|
||||
<button
|
||||
className="btn btn-success btn-sm"
|
||||
onClick={() => handleRespondToInvite(challenge.id, 'accepted')}
|
||||
disabled={respondingTo === challenge.id}
|
||||
>
|
||||
Accept
|
||||
{respondingTo === challenge.id ? '...' : 'Accept'}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger btn-sm"
|
||||
onClick={() => handleRespondToInvite(challenge.id, 'rejected')}
|
||||
disabled={respondingTo === challenge.id}
|
||||
>
|
||||
Decline
|
||||
{respondingTo === challenge.id ? '...' : 'Decline'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -141,7 +154,7 @@ export default function ChallengeList() {
|
||||
)}
|
||||
|
||||
{/* Search/Create */}
|
||||
<div style={{ marginBottom: '2rem', position: 'relative' }}>
|
||||
<div style={{ marginBottom: '2rem', position: 'relative' }} ref={searchRef}>
|
||||
<input
|
||||
type="text"
|
||||
className="input"
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import api from '../api';
|
||||
import { useClickOutside } from '../hooks/useClickOutside';
|
||||
|
||||
export default function Friends() {
|
||||
const [friends, setFriends] = useState([]);
|
||||
@@ -9,6 +11,11 @@ export default function Friends() {
|
||||
const [searchResults, setSearchResults] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchTimeout, setSearchTimeout] = useState(null);
|
||||
const [responding, setResponding] = useState(null);
|
||||
const [sending, setSending] = useState(null);
|
||||
const searchRef = useRef(null);
|
||||
|
||||
useClickOutside(searchRef, () => setSearchResults([]));
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
@@ -57,22 +64,29 @@ export default function Friends() {
|
||||
};
|
||||
|
||||
const handleSendRequest = async (userId) => {
|
||||
setSending(userId);
|
||||
try {
|
||||
await api.sendFriendRequest(userId);
|
||||
setSearchQuery('');
|
||||
setSearchResults([]);
|
||||
alert('Friend request sent!');
|
||||
toast.success('Friend request sent!');
|
||||
} catch (err) {
|
||||
alert('Failed to send request: ' + err.message);
|
||||
toast.error('Failed to send request: ' + err.message);
|
||||
} finally {
|
||||
setSending(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRespond = async (requestId, status) => {
|
||||
setResponding(requestId);
|
||||
try {
|
||||
await api.respondToFriendRequest(requestId, status);
|
||||
toast.success(status === 'accepted' ? 'Friend request accepted!' : 'Friend request declined');
|
||||
await loadData();
|
||||
} catch (err) {
|
||||
alert('Failed to respond: ' + err.message);
|
||||
toast.error('Failed to respond: ' + err.message);
|
||||
} finally {
|
||||
setResponding(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -86,7 +100,7 @@ export default function Friends() {
|
||||
<h1 style={{ marginBottom: '2rem' }}>Friends</h1>
|
||||
|
||||
{/* Search */}
|
||||
<div className="card" style={{ marginBottom: '2rem', position: 'relative' }}>
|
||||
<div className="card" style={{ marginBottom: '2rem', position: 'relative' }} ref={searchRef}>
|
||||
<h3 style={{ marginBottom: '1rem' }}>Add Friends</h3>
|
||||
<input
|
||||
type="text"
|
||||
@@ -127,8 +141,9 @@ export default function Friends() {
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={() => handleSendRequest(user.id)}
|
||||
disabled={sending === user.id}
|
||||
>
|
||||
Add Friend
|
||||
{sending === user.id ? 'Sending...' : 'Add Friend'}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
@@ -151,14 +166,16 @@ export default function Friends() {
|
||||
<button
|
||||
className="btn btn-success btn-sm"
|
||||
onClick={() => handleRespond(req.id, 'accepted')}
|
||||
disabled={responding === req.id}
|
||||
>
|
||||
Accept
|
||||
{responding === req.id ? '...' : 'Accept'}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger btn-sm"
|
||||
onClick={() => handleRespond(req.id, 'rejected')}
|
||||
disabled={responding === req.id}
|
||||
>
|
||||
Reject
|
||||
{responding === req.id ? '...' : 'Reject'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useAuth } from '../AuthContext';
|
||||
|
||||
export default function Login() {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await login(email, password);
|
||||
toast.success('Welcome back!');
|
||||
navigate('/challenges');
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
toast.error(err.message || 'Login failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -50,7 +50,6 @@ export default function Login() {
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<button type="submit" className="btn btn-primary" style={{ width: '100%', marginTop: '1rem' }} disabled={loading}>
|
||||
{loading ? 'Logging in...' : 'Login'}
|
||||
</button>
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useAuth } from '../AuthContext';
|
||||
|
||||
export default function Register() {
|
||||
const [email, setEmail] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await register(email, username, password);
|
||||
toast.success('Account created successfully!');
|
||||
navigate('/challenges');
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
toast.error(err.message || 'Registration failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -62,7 +62,6 @@ export default function Register() {
|
||||
minLength={6}
|
||||
/>
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
<button type="submit" className="btn btn-primary" style={{ width: '100%', marginTop: '1rem' }} disabled={loading}>
|
||||
{loading ? 'Creating account...' : 'Register'}
|
||||
</button>
|
||||
|
||||
Reference in New Issue
Block a user