I'm learning NextJS and currently I don't understand the differences, and when I should use getStaticProps & getStaticPaths compared to useRouter().query.
So far to me, it seems like they can do the same thing for my very simple book-listing site: getting the ID from the URL e.g: "localhost:3000/books/book1" and use that ID to fetch and display the corresponding item from a database (simulated with some async functions below)
These are my 2 approaches written in pages/books/[bookId].tsx, and they both work.
Using getStaticPaths, getStaticProps
export async function getStaticPaths() {
const books: Book[] = await getBooksAsync();
const paths = books.map((book) => {
return { params: { bookId: book.id } };
});
return {
paths,
fallback: false,
};
}
export async function getStaticProps(context: GetStaticPropsContext) {
const params = context.params!;
const bookId = params.bookId as string;
const book = await getBookByIdAsync(bookId);
return {
props: {
book,
},
};
}
const Book = ({ book }: { book: Book }) => {
return (
<div>
<p>Book Id: {book.id}</p>
<p>Title: {book.title}</p>
<p>Year: {book.year}</p>
<p>Reviews Count: {book.reviews.length}</p>
</div>
);
};
Using useRouter().query
const Book = () => {
const router = useRouter();
const query = router.query;
const bookId = query.bookId as string;
const [book, setBook] = useState<Book>();
useEffect(() => {
async function getBooks() {
const _book = await getBookByIdAsync(bookId);
setBook(_book);
}
getBooks();
}, [bookId]);
if (!book) return <></>;
return (
<div>
<p>Book Id: {book.id}</p>
<p>Title: {book.title}</p>
<p>Year: {book.year}</p>
<p>Reviews Count: {book.reviews.length}</p>
</div>
);
};