Skip to content

Instantly share code, notes, and snippets.

@sand97
Created January 3, 2022 00:51
Show Gist options
  • Save sand97/fe6cd4fd29cdb044589a710afd8aba8e to your computer and use it in GitHub Desktop.
Save sand97/fe6cd4fd29cdb044589a710afd8aba8e to your computer and use it in GitHub Desktop.
Next.js static file optimization
import { useRouter } from 'next/router'
import Head from 'next/head'
export default function Fact({ fact }) {
const router = useRouter()
return (
<div style={{ textAlign: 'center' }}>
<h1>A fact about cat</h1>
<br/>
<p>{fact}</p>
</div>
)
}
// This function gets called at build time
export async function getStaticPaths() {
const paths = ['45', '90', '150'].map(length => ({
params: {length}
}));
return {paths, fallback: true}
}
export async function getStaticProps({ params }) {
console.info('get data from API');
const response = await fetch(`https://catfact.ninja/fact?max_length=${params.length}`);
const {fact} = await response.json();
return {
props: {
fact,
},
revalidate: false, // One year in seconds
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment