react themoviedb api

해적왕·2022년 11월 6일
0
post-custom-banner

.env

REACT_APP_API_KEY=
REACT_APP_API=https://api.themoviedb.org/3/movie/
REACT_APP_SEARCH=https://api.themoviedb.org/3/search/movie/
REACT_APP_IMG=https://image.tmdb.org/t/p/w500/

Home.jsx

import {useState, useEffect} from 'react';

const movieURL = process.env.REACT_APP_API;
const apiKey = process.env.REACT_APP_API_KEY;

const Home = () => {
  const [topMovies, setTopMovies] = useState([]);
  const getTopRatedMovies = async (url) => {
    const res = await fetch(url);
    const data = await res.json();
    
    setTopMovies(data.results);
  }
  useEffect(()=>{
    const topRatedURL = `${movieURL}top_rated?${apiKey}`;
    getTopRatedMovies(topRatedURL);
  },[])
  return (
    <div>
    {topMovies && topMovies.map((movie)=>{
      return (
        <>
        {movie.title}
        </>
      )
    })}
    </div>
  )
}
export default Home

search

import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import MovieCard from "../components/MovieCard";
import "./MovieGrid.css";

const searchURL = process.env.REACT_APP_SEARCH;
const apiKey = process.env.REACT_APP_API_KEY;

const Search = () => {
  const [searchParams] = useSearchParams();
  const [movies, setMovies] = useState([]);
  const query = searchParams.get("q");

  const getSearchedMovies = async (url) => {
    const res = await fetch(url);
    const data = await res.json();

    setMovies(data.results);
  };
  useEffect(() => {
    const searchWithQueryURL = `${searchURL}?${apiKey}&query=${query}`;
    getSearchedMovies(searchWithQueryURL);
  }, [query]);

  return (
    <div className="container">
      <h2>
        Resultados para: <span>{query}</span>
        <div>
      {movies.length === 0 && <p>loading</p>}
      {movies.length > 0 && movies.map((movie)=><MovieCard key={movie.id} movie={movie}/>)}</div>
      </h2>
    </div>
  );
};
export default Search;
profile
프론트엔드
post-custom-banner

0개의 댓글