1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| function MovieDetails({ selectedId, onCloseMovie, onAddWatched, watched }) { const [movie, setMovie] = useState({}); const [isLoading, setIsLoading] = useState(false); const [userRating, setUserRating] = useState("");
const countRef = useRef(0);
useEffect( function () { if (userRating) countRef.current++; }, [userRating] );
const isWatched = watched.map((movie) => movie.imdbID).includes(selectedId); const watchedUserRating = watched.find( (movie) => movie.imdbID === selectedId )?.userRating;
const { Title: title, Poster: poster, Runtime: runtime, imdbRating, Plot: plot, Released: released, Actors: actors, Director: director, Genre: genre, } = movie;
function handleAdd() { const newWatchedMovie = { imdbID: selectedId, title, poster, imdbRating: Number(imdbRating), runtime: Number(runtime.split(" ").at(0)), userRating, countRatingDecisions: countRef.current, }; onAddWatched(newWatchedMovie); onCloseMovie(); }
useKey("Escape", onCloseMovie);
useEffect( function () { setIsLoading(true); async function getMovieDetails() { const res = await fetch( `http://www.omdbapi.com/?apikey=${KEY}&i=${selectedId}` ); const data = await res.json(); setMovie(data); setIsLoading(false); } getMovieDetails(); }, [selectedId] );
useEffect( function () { if (!title) return; document.title = `Movie|${title}`;
return function () { document.title = "usePopcorn"; }; }, [title] );
return ( <div className="details"> {isLoading ? ( <Loader /> ) : ( <> <header> <button className="btn-back" onClick={onCloseMovie}> ← </button> <img src={poster} alt={`Poster of ${movie}`} /> <div className="details-overview"> <h2>{title}</h2> <p> {released} • {runtime} </p> <p>{genre}</p> <p> <span>🌟</span> {imdbRating} IMDb rating </p> </div> </header> <section> <div className="rating"> {!isWatched ? ( <> <StarRating maxRating={10} size={36} onSetRating={setUserRating} /> {userRating > 0 && ( <button className="btn-add" onClick={handleAdd}> + Add to list </button> )} </> ) : ( <p>You rated with this movie {watchedUserRating}🌟</p> )} </div> <p> <em>{plot}</em> </p> <p>Starring: {actors}</p> <p>Directed by: {director}</p> </section> </> )} </div> ); }
|