import React, { useState, useEffect } from 'react'; import './App.css'; function App() { const [movies, setMovies] = useState([]); const [selectedMovie, setSelectedMovie] = useState(''); const [recommendations, setRecommendations] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); useEffect(() => { fetch('/api/movies') .then(res => res.json()) .then(data => { if(Array.isArray(data.movies)){ setMovies(data.movies); if(data.movies.length > 0){ setSelectedMovie(data.movies[0]); } } else { setError('Invalid movies list received'); } }) .catch(() => setError('Failed to fetch movie list')); }, []); const handleRecommend = () => { if (!selectedMovie) return; setLoading(true); setError(''); setRecommendations([]); fetch(`/api/recommend?title=${encodeURIComponent(selectedMovie)}`) .then(res => { if (!res.ok) throw new Error('Failed to fetch recommendations'); return res.json(); }) .then(data => { setRecommendations(data.recommendations || []); setLoading(false); }) .catch(() => { setError('Failed to get recommendations'); setLoading(false); }); }; // Fetch poster with TMDB API key - replace with your key or environment variable const fetchPosterUrl = async (movieId) => { const apiKey = "YOUR_TMDB_API_KEY"; // <--- replace here const url = `https://api.themoviedb.org/3/movie/${movieId}?api_key=${apiKey}`; try { const response = await fetch(url); if (!response.ok) throw new Error('Failed fetching poster'); const data = await response.json(); if (data.poster_path) { return `https://image.tmdb.org/t/p/w500/${data.poster_path}`; } } catch { // Ignore poster fetching errors } return "https://via.placeholder.com/500x750.png?text=No+Poster"; }; const Poster = ({ movieId, title }) => { const [posterUrl, setPosterUrl] = useState("https://via.placeholder.com/500x750.png?text=Loading..."); useEffect(() => { let mounted = true; fetchPosterUrl(movieId).then(url => { if(mounted) setPosterUrl(url); }); return () => { mounted = false; }; }, [movieId]); return (
{title}
Select a movie you like to get 10 similar recommendations.
{error}
}