0

Here in Image you can see the error and the code i've tried.Server Error TypeError: Cannot read properties of undefined (reading 'map')

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

here I'm trying to map data hardcoded to my .json files in my project. But this error for map method getting.

import React, { useState } from "react";
import Link from "next/link";
import * as fs from 'fs';

// setp 1: Collect all the files from blogdata directory
// setp 2: Iterate through the and display them
const blog = (props) => {
  console.log(props);
  const [blogs, setBlogs] = useState(props.allblogs);
  
  return (
    <>
      <div className="section flex flex-col items-center mb-10">
        {blogs.map((blogitem) => {
          return (
            <div
              key={blogitem.slug}
              className="cursor-pointer w-2/3 space-y-2 border-[2px] shadowimg p-5 border-black rounded-lg mt-10 flex flex-col justify-start"
            >
              <Link href={`/blogpost/${blogitem.slug}`}>
                <h3 className="text-xl md:text-3xl font-semibold">
                  {blogitem.title}
                </h3>
                <p className="text-sm md:text-base my-4">
                  {blogitem.content.substr(0, 300)}....
                </p>
                <p className="text-right font-semibold md:text-lg">
                  -{blogitem.author}
                </p>
              </Link>
            </div>
          );
        })}
      </div>
    </>
  );
};

export async function getStaticProps(context) {
  let data = await fs.promises.readdir("blogdata");
  let myfile;
  let allBlogs = [];
  for (const element of data) {
      const item = element;
      console.log(item)
      myfile = await fs.promises.readFile(('blogdata/' + item), 'utf-8')
      allBlogs.push(JSON.parse(myfile))
  }

  return {
      props: { allBlogs }, // will be passed to the page component as props
  }
}

export default blog;

2 Answers2

1

You're passing allBlogs in static props, while accessing allblogs in the main component.

const [blogs, setBlogs] = useState(props.allBlogs);

Also as a good practice, add conditional returns for when the blogs are null.

if (blogs !== []) {
   return <></> // Your main component
} else {
   return <></> // Some error or loading
}
Aahan Agarwal
  • 391
  • 2
  • 6
0

You can handle it with null/undefined check like this

 const [blogs, setBlogs] = useState(props?.allblogs ?? []);

if you need extra checks in case blogs is set to null/undefined

return (
    <>
      <div className="section flex flex-col items-center mb-10">
        {blogs?.map((blogitem) => {
          return (

There is a good article about null checks and nullish coalescing

Hope it helps in someway

Azzy
  • 1,717
  • 2
  • 13
  • 17