0

I have an object including web content:

const postContent = {
    post1: {
        title: 'Post 1',
        content: 'Content 1'
    },
    post2: {
        title: 'Post 2',
        content: 'Content 2'
    }
}

And a dynamic [post].js:

import { postContent } from "../../lib";
import { useRouter } from "next/router";

const postWeb = () => {
    const router = useRouter();
    const { post } = router.query;
    const postGet = postContent[post]
    console.log(postGet)
    return (
        <div>
            {postGet.title}
        </div>
    );
}

export default postWeb;

I use [post] to get the object from postContent like postContent.post1 (depend on URL like /post/post1 or /post/post2) I use console.log(postGet) and receive an object: {title: 'Post 1', content: 'Content 1'}. But when I use postGet.title, it will be undefined and receive an error:

TypeError: Cannot read properties of undefined (reading 'title')

This error happened while generating the page. Any console logs will be displayed in the terminal window

I don't know how to fix this, I'm figured out how to use dynamic route with content in Nextjs. Can anyone help me with these or can give me tutorials about these?

Thank you.

Khoa Nguyễn
  • 97
  • 1
  • 9
  • In statically optimized pages the query parameters are not available on initial render. You have to wait for the router to be ready, with `router.isReady`, before accessing `router.query.post`. See [useRouter/withRouter receive undefined on query in first render](https://stackoverflow.com/questions/61040790/userouter-withrouter-receive-undefined-on-query-in-first-render). – juliomalves May 08 '22 at 12:17

1 Answers1

1

Problem

TypeError: Cannot read properties of undefined (reading 'title')

In your initial rendering, you are accessing a property of an object that is initially doesn't exist.

Solution

Consider adding default value or short circuiting

  return (
        <div>
            {postGet && postGet.title}
        </div>
    );
Amr
  • 646
  • 1
  • 6
  • 21