16. Next.js Tutorial (3). Dynamic Routes. Async functions getStaticPaths and getStaticProps

1. Dynamic page


1. Create a page at /pages/posts/[id].js where the brackets "[]" means a dynamic page

2. This file must contain:

  • A React component to render this page
  • getStaticPaths async function that returns an array of possible values of id. And has the fallback property. This function is called at build time and needs to be exported (export async function getStaticPaths() )
  • getStaticProps async which fetches necessary data for the post with the id; and needs to be exported too (export async function getStaticProps() )
The fallback property of the getStaticPaths means:
  • If fallback is false, then any paths not returned by getStaticPaths will result in a 404 page.
  • If fallback is true, it will serve the paths generated at build time. If it was not generated at build time, Next.js will serve a "fallback" version of the page.
  • If fallback is blocking, the new paths will be server.side rendered with getStaticProps.

2. Render Markdown (MD files)


Only, in the case you have MD (markdown) format document, install the remark library 
npm install remark remark-html

3. Formatting the date and using CSS


In order to format the date, use the date-fns library
npm install date-fns

Create a function like this one
import { parseISO, format } from 'date-fns';

export default function Date({ dateString }:  {dateString : string}) {
  const date = parseISO(dateString);
  return <time dateTime={dateString}>{format(date, 'LLLL d, yyyy')}</time>;
}
Now, when displaying any info you can include the date as follows:

<Date dateString={postData.date} /> 

To use CSS:

1. Add this import at the top of the file: import
import utilStyles from '../../styles/utils.module.css';

2. Use className
<h1 className={utilStyles.headingXl}>{postData.title}</h1>


Add this code to render a list of links to the entries

<ul className={utilStyles.list}>
{allPostsData.map(pd => (
  <li className={utilStyles.listItem} key={pd.id}>
    <>
      <Link href={`/posts/${pd.id}`}>{pd.title}</Link>
      <br />
      <small className={utilStyles.lightText}>
        <Date dateString={pd.date} />
      </small>
    </>
  </li>
  ))}
</ul>

5. We can obtain the ids from a REST call

export async function getAllPostIds() {
  // Instead of the file system,
  // fetch post data from an external API endpoint
  const res = await fetch('https://.../posts');
  const posts = await res.json();
  return posts.map((post) => {
    return {
      params: {
        id: post.id,
      },
    };
  });
}

6. Development vs. Production

- In development (npm run dev or yarn dev), getStaticPaths runs on every request.
- In production, getStaticPaths runs at build time.

7. Catch-all Routes( nested routes)

Adding three dots (...) inside the brackets can represent nested routes for instance

pages/posts/[...id].js   matches /posts/a, but also /posts/a/b, /posts/a/b/c, and so on.

But getStaticPaths, you must return an array as the value of the id:
return [
  {
    params: {
      // Statically Generates /posts/a/b/c
      id: ['a', 'b', 'c'],
    },
  },
  //...
];
And the params.id from 

export async function getStaticProps({ params }) {

must be an array like ['a', 'b', 'c']

8. Router, 404 page, Error pages.

If you want to use a router because Link may not adapt to your needs, use the useRooter hook
You can create a custon 404 page. the file is my-app10/pages/404.js. Here is an example:
// pages/404.js
export default function Custom404() {
  return <h1>404 - Page Not Found</h1>;
}
You can use the Error Pages for othe kind of errors.



Comentarios

Entradas populares de este blog

14. Next.js Tutorial (1)

18. Next.js Tutorial (5). Deploying. HTTPS