Created
February 16, 2022 14:33
-
-
Save ibelick/b06fe147d7fcd9c65494f665944c4c7a to your computer and use it in GitHub Desktop.
Next.js basic GetStaticProps+GetStaticPaths with TypeScript
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 type { GetStaticPaths, GetStaticProps, NextPage } from "next"; | |
import { ParsedUrlQuery } from "querystring"; | |
interface Data { | |
title: string; | |
} | |
interface HomePageProps { | |
data: Data; | |
} | |
const Home: NextPage<HomePageProps> = (props) => { | |
return ( | |
<div> | |
<h1>{props.data.title}</h1> | |
</div> | |
); | |
}; | |
interface Params extends ParsedUrlQuery { | |
uid: string; | |
} | |
export const getStaticProps: GetStaticProps<HomePageProps, Params> = async ( | |
context | |
) => { | |
const { uid } = context.params!; | |
try { | |
const { data, errors } = await someQuery(`get/${uid}`); | |
if (errors || !data) { | |
return { notFound: true }; | |
} | |
return { props: { data } }; | |
} catch (err) { | |
return { notFound: true }; | |
} | |
}; | |
export const getStaticPaths: GetStaticPaths<Params> = async () => { | |
const paths = Array.from({ length: 10 }, (_, index) => ({ | |
params: { | |
uid: (index + 1).toString(), | |
}, | |
})); | |
return { | |
paths, | |
fallback: false, | |
}; | |
}; | |
export default Home; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment