Skip to content

Instantly share code, notes, and snippets.

@tsh-code
Last active March 23, 2022 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsh-code/c7672784d64feff5c5b9ca3b50f9df0b to your computer and use it in GitHub Desktop.
Save tsh-code/c7672784d64feff5c5b9ca3b50f9df0b to your computer and use it in GitHub Desktop.
ssr-next-js
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