next.jsgetstaticprops

How to fix "TypeError: Cannot read properties of undefined (reading 'length')" in nextjs?


enter image description here I guess getStaticProps doesn't work well, but I don't know exact.. Is getStaticProps render after render Main function?

below code is index.js

import Main from "../components/main/main";

export default function Home() {
  return <Main/>;
}

below code is main.js


export async function getStaticProps() {
  const files = fs.readdirSync("ContentDetail");

  const getposts = files.map((fileName) => {
    const slug = fileName.replace(".md", "");
    const readFile = fs.readFileSync(`ContentDetail/${fileName}`, "utf-8");
    const { data: info, content } = matter(readFile);
    return {
      info,
      slug,
    };
  });

  return {
    props: {
      getposts,
    },
  };
}

export default function Main({ getposts }) {
  const [posts, setPosts] = useState(getposts);
  const [groupstyle, setGroupstyle] = useState();
  const [pages, setPages] = useState([]);
  const [totalPages, setTotalPages] = useState(Math.ceil(posts.length / 7));
  const [itemOffset, setItemOffset] = useState(0);

  const currentItems = posts.slice(itemOffset, itemOffset + 7);

  const contentRef = useRef([]);
  const backRef = useRef(null);
  ......


Solution

  • Change the following line:

    const [totalPages, setTotalPages] = useState(Math.ceil(posts && posts.length / 7));