우리가 받아올 결과 데이터를 확인하는 것은 매우 중요하다.
주소창에 미리 입력해서 확인해보기
api.ts
const API_KEY = "api사이트에서 받아온 키 ";
const BASE_PATH = "https://api.themoviedb.org/3";
export function getMovies() {
return fetch(`${BASE_PATH}/movie/now_playing?api_key=${API_KEY}`).then(
(response) => response.json()
);
}
export default getMovies;
Home.tsx
import { useQuery } from "react-query";
import { getMovies } from "../api";
function Home() {
const { data, isLoading } = useQuery(["movies", "nowPlaying"], getMovies);
console.log(data, isLoading);
return <div style={{ height: "200vh" }}></div>;
}
export default Home;
react-query 버전충돌문제
react18과 react-query 4 버전 충돌에 따라 다음 코드로 설치
npm i @tanstack/react-query
TheMovieDB API Key
https://www.themoviedb.org/settings/api?language=ko
TheMovieDB API Document
https://developers.themoviedb.org/3/movies/get-now-playing
TheMovieDB Image가져오기
이미지 파일명 앞에 https://image.tmdb.org/t/p/original/ 붙이기
BASE_PATH
https://api.themoviedb.org/3/
React Query
```
const { isLoading, error, data } = useQuery('repoData', () =>
fetch('https://api.github.com/repos/tannerlinsley/react-query').then(res =>
res.json()
)
)
```
https://react-query.tanstack.com/overview
typescript를 사용하기위해서, 우리는 api응답의 타입을 설정해야 원하는 자도완성 기능을 사용 할 수 있다.
api.ts에 typescript 형태 정하기
api.ts
export interface IMovie {
id: number;
backdrop_path: string;
poster_path: string;
title: string;
overview: string;
}
export interface IGetMoviesResult {
dates: {
maximum: string;
minimum: string;
};
page: number;
results: IMovie[];
total_pages: number;
total_results: number;
}
utils.ts
export function makeImagePath(id: string, format?: string) {
return `https://image.tmdb.org/t/p/${format ? format : "original"}/${id}`;
}
import { makeImagePath } from "../utils";
const Wrapper = styled.div`
background: black;
`;
const Loader = styled.div`
height: 20vh;
display: flex;
justify-content: center;
align-items: center;
`;
const Banner = styled.div<{ bgPhoto: string }>`
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
padding: 60px;
background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
url(${(props) => props.bgPhoto});
background-size: cover;
`;
const Title = styled.h2`
font-size: 68px;
margin-bottom: 10px;
`;
const Overview = styled.p`
font-size: 36px;
width: 50%;
`;
function Home() {
const { data, isLoading } = useQuery<IGetMoviesResult>(
["movies", "nowPlaying"],
getMovies
);
return (
<Wrapper>
{isLoading ? (
<Loader>Loading... </Loader>
) : (
<>
<Banner
bgPhoto={makeImagePath(
data?.results[0].backdrop_path || "" //fallback
)}
>
<Title>{data?.results[0].title}</Title>
<Overview>{data?.results[0].overview}</Overview>
</Banner>
</>
)}
</Wrapper>
);
}
export default Home;
'코딩 > Today I Learn' 카테고리의 다른 글
#5 MOVIE MODAL (0) | 2022.10.31 |
---|---|
#3 NETFLIX SLIDER (0) | 2022.10.25 |
#1 NETFLIX HEADER (2) | 2022.10.11 |
React animaiton #framer-motion (0) | 2022.09.26 |
React Js Master #10 Ref,CrossBoardMovement (0) | 2022.08.03 |