Advertisement
Thenlie

Untitled

Dec 17th, 2022
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useLoaderData } from 'react-router-dom';
  2. import { useState, useEffect } from 'react';
  3. import { getMoviesByName, getMovieDetails } from '../helpers/getMovieUtils';
  4. import { ShowCard, ShowCarousel } from '../components';
  5. import { MovieData, MovieDetailsData } from '../types/tmdb';
  6.  
  7. /**
  8.  * This loader is mostly built straight from the react-router docs
  9.  * https://reactrouter.com/en/main/components/form#get-submissions
  10.  *
  11.  * @param request | HTTP GET request from the SearchInput component
  12.  * @returns {Promise<string>} | the users query
  13.  */
  14. export async function loader({ request }: { request: Request }): Promise<string> {
  15.     // get the query parameters from the URL
  16.     const url = new URL(request.url);
  17.     const query = url.searchParams.get('q');
  18.     return query as string;
  19. }
  20.  
  21. /**
  22.  * @returns {JSX.Element} results page after user input
  23.  */
  24. export default function SearchResultsScreen(): JSX.Element {
  25.     const query: string = useLoaderData() as string;
  26.     const [movieDetails, setMovieDetails] = useState<MovieDetailsData[]>([]);
  27.     const [loading, setLoading] = useState<boolean>(true);
  28.  
  29.     useEffect(() => {
  30.         const handler = async () => {
  31.             const movieData: MovieData = await getMoviesByName(query);
  32.             const movieArr = [];
  33.             for (let i = 0; i < movieData.results.length; i++) {
  34.                 const movie = await getMovieDetails(movieData.results[i].id);
  35.                 movieArr.push(movie);
  36.                 setMovieDetails(movieArr);
  37.                 setLoading(false);
  38.             }
  39.         };
  40.         handler();
  41.     }, []);
  42.  
  43.     console.log(movieDetails);
  44.  
  45.     if (loading) return <p>Loading...</p>;
  46.  
  47.     return (
  48.         <>
  49.             <h1 data-testid="search-results-heading">Search Results Page</h1>
  50.             <p>Query: {query}</p>
  51.             {movieDetails.map((item, i) => (
  52.                 <ShowCard key={i} details={item} />
  53.             ))}
  54.             <ShowCarousel />
  55.         </>
  56.     );
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement