import Image from 'next/image' import { Layout, Text, Page, Code, Link, List } from '@vercel/examples-ui' import { GetStaticProps } from 'next' import useSWR from 'swr' import { useEffect, useState } from 'react' import board from '../public/board.jpg' interface Product { id: string title: string description: string image: string price: string stock: number } interface Props { product: Product } const fetcher = (input: RequestInfo, init?: RequestInit) => fetch(input, init).then((res) => res.json()) export const getStaticProps: GetStaticProps = async () => { return { props: { product: { id: 'mug-nextjs', title: 'Vercel Mug', description: 'Limited Edition', image: '/mug.png', price: 150, stock: 5, }, }, } } function ProductCard({ product }: Props) { const [isAdded, toggleAdded] = useState(false) const { data: stock } = useSWR(`/api/product/${product.id}/stock`, fetcher, { refreshInterval: 5000, }) const isLoading = stock === undefined useEffect(() => { let timeout: NodeJS.Timeout if (isAdded) { timeout = setTimeout(() => { toggleAdded(false) }, 1500) } return () => clearTimeout(timeout) }, [isAdded]) return (
{product.title}

{product.title}

{product.description} {isLoading ? `` : `(${stock} left)`}

USD {product.price}

{isLoading ? ( Loading... ) : ( <> {isAdded ? ( Added! ) : ( <> {stock > 0 ? ( toggleAdded(true)} className="py-4 px-6 text-lg w-full bg-black text-center text-white hover:text-white rounded-md hover:bg-gray-900" > Add to cart ) : ( No stock available )} )} )}
) } function Home({ product }: Props) { return (
Combining data fetching strategies Next.js has two forms of pre-rendering: Static Generation and Server-side Rendering. The difference is in when it generates the HTML for a page.
  • Static Generation {' '} is the pre-rendering method that generates the HTML at build time. The pre-rendered HTML is then reused on each request.
  • Server-side Rendering {' '} is the pre-rendering method that generates the HTML on each request.
  • Sometimes we need to have data in our page that is not static and we tend to move away from getStaticProps to{' '} getServerSideProps.

    A real-world example We have an e-commerce product page that is statically generated, but we need to disable the "Add to cart" button if we have no stock. We can combine our data fetching strategies to get the best of both worlds. We will still generate our product page statically but we will fetch our stock periodically to update our UI. Graph showing how the page is generated at build time and updated client-side This page is statically generated so you can see the example below. We are using SWR to fetch the stock status every 5 seconds and disable the "Add to cart" button if we have no stock. The stock is a random number so you can see the button getting disabled and enabled several times.

    ) } Home.Layout = Layout export default Home