Last active
March 23, 2022 13:29
-
-
Save tsh-code/c7672784d64feff5c5b9ca3b50f9df0b to your computer and use it in GitHub Desktop.
ssr-next-js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { GetServerSidePropsContext, GetServerSidePropsResult } from 'next'; | |
type Product = { | |
id: string; | |
title: string; | |
} | |
type SearchResultsPageProps = { | |
products: Array<Product>; | |
} | |
const SearchResultsPage = ({ products }: SearchResultsPageProps) => ( | |
<div> | |
{products.map((product) => (<p key={product.id}>{product.title}</p>))} | |
</div> | |
) | |
export async function getServerSideProps({ res, query }: GetServerSidePropsContext): Promise<GetServerSidePropsResult<SearchResultsPageProps>> { | |
const category = query?.category; | |
if (!category) { | |
return { | |
redirect: { | |
destination: '/' | |
} | |
} | |
} | |
const data = await fetch(`http://external-api.com/products?category=${category}`); | |
const products = await data.json(); | |
if (products.length === 0) { | |
return { | |
notFound: true | |
} | |
} | |
return { | |
props: { | |
products, | |
} | |
} | |
} | |
export default ProductsPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment