import { useState, useEffect } from "react";
import Seo from "../components/Seo";
const API_KEY = "10923b261ba94d897ac6b81148314a3f";
export default function Home() {
const [movies, setMovies] = useState();
useEffect(() => {
(async () => {
const { results } = await (
await fetch(
`https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`
)
).json();
console.log(results)
setMovies(results);
})();
}, []);
return (
<div>
<Seo title="Home" />
{!movies && <h4>Loading...</h4>}
{movies?.map((movie) => (
<div key={movie.id}>
<h4>{movie.original_title}</h4>
</div>
))}
</div>
);
}
next.config.js파일에서 Redirect, Rewrite를 설정할 수 있다.
module.exports = {
reactStrictMode: true,
async redirects() {
return [
{
source: "/old-blog/:path*", // user가 /old-blog로 이동하면,
destination: "/new-blog/:path*", // user를 /new-blog로 보낸다.
permanent: false, // 브라우저나 검색엔진이 이 정보를 기억하는지 여부가 결정된다.
}
]
}
}
// *으로 그 뒤의 url 모두를 가져올 수 있다.
API KEY가 공개되어있다! 비공개로 해주어야 한다. rewrite를 사용하면 된다.
user를 redirect 시키지만, URL은 변하지 않는다.
server에서 Mask되어 가려지기 때문에 보이지 않는다!
const API_KEY = process.env.API_KEY;
module.exports = {
reactStrictMode: true,
async redirects() {
...
}
async rewrites() {
source: "/api/movies",
destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`,
}
}
// *으로 그 뒤의 url 모두를 가져올 수 있다.
.env 파일을 추가하고 API_KEY를 입력해준다.
.gitignore에 추가하는 것도 잊지 말자.
API_KEY = 10923b261ba94d897ac6b81148314a3f
server에서만 실행된다.
getServerSideProps() function은 object를 return한다.
object에는 props라는 key를 가지고 있다.
props에 원하는 데이터를 넣을 수 있다.
props는 page로 전달된다.
export async function getServerSideProps() {
const { results } = await (await fetch(`http://localhost:3000/api/movies`)).json();
return {
props: {
results,
},
};
}
/movies/:id 처럼 url에 변수가 있는 경우
NextJS에서는 /movies 폴더를 만들고 내부에 [id].js 파일을 만들어서 작성하면 된다.
id는 useRouter를 이용해서 값을 받아올 수 있다.
import { useRouter } from "next/router";
export default function Detail(){
const router = useRouter();
console.log(router)
return "detail"
}
query에 원하는 정보를 담아서 전달할 수 있다.
as에 원하는 url을 입력해서 설정할 수 있다. query가 마스킹되도록 처리 가능하다.
const router = useRouter();
const onClick = (id, title) => {
router.push(
{
pathname: `/movies/${id}`,
query: {
title,
},
},
`/movies/${id}`
);
};
<Link
href={{
pathname: `/movies/${movie.id}`,
query: {
title: movie.original_title,
},
}}
as={`/movies/${movie.id}`}
>
<a>{movie.original_title}</a>
</Link>
파일명을 [...params].js로 하면 여러개의 params를 모두 받아올 수 있다.
컴포넌트 내부에서 router를 사용하면 router는 front(client-side)에서만 실행된다.
하지만 URL에 들어있는 영화제목을 사용해서 구글 SEO에 최적화하고, pre-render하고 싶다면 getServerSideProps를 사용해서 server-side에서 정보를 얻으면 된다.
/pages 폴더에 404.js 파일을 만들고 커스텀하면 된다!
export default function NotFound() {
return "what are u doing here?"
}