Encountering an issue in Next.js when using getStaticProps: reading 'map' of undefined properties

The Image above shows the error and the code I have attempted.Server Error TypeError: Cannot read properties of undefined (reading 'map')

This particular error occurred during the page generation process. Any console logs will appear in the terminal window.

In this case, I am attempting to map hardcoded data from .json files in my project. However, I keep encountering this error related to the map method.

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

// Step 1: Retrieve all files from the blogdata directory
// Step 2: Iterate through 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;

Answer №1

In your code, you are passing the variable allBlogs as a prop, but trying to access it as allblogs in the main component.

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

To improve this, consider adding conditional statements to handle cases where the value of blogs is null.

if (blogs !== []) {
   return <></> // Your main component
} else {
   return <></> // Display error or loading message
}

Answer №2

To handle potential null or undefined values, you can use the following code snippet:

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

If you require additional checks for when blogs is null or undefined:

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

For more information on null checks and nullish coalescing, check out this informative article: null checks and nullish coalescing

I trust this will be beneficial in some way.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to eliminate empty arrays from my data?

I'm dealing with this PHP code snippet. public function display_children($parent,$level){ try { $cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?'); $cmd->execute(array($parent)); ...

How can one save a text value element from a cascading list in ASP.NET MVC?

I have recently started learning about javascript, jquery, and ajax. In my model, I have defined the following classes: namespace hiophop.Models { public class CarMake { public class Category { public int CategoryID { g ...

The issue of Angular UI Bootstrap buttons not updating persists even after the removal of an

My Radio-bottoms are powered by an Array for a Multi-Choice answer setup. <div ng-repeat="option in options"> <div> <button type="button" style="min-width: 100px" class="btn btn-default" ng-model="question.answer" btn-radio="' ...

What is the purpose of the _buildManifest.js file in nextjs and is there a way to deactivate it?

Our team is currently working on a website using NextJS. We recently discovered a file called _buildManifest.js in the source code of our site, which seems to contain a list of all the pages defined on our website. This is not something we want to have v ...

Controller receiving empty object array from FormData

I am encountering an issue with my ajax call to the controller, where I am passing FormData() containing an array of objects and other properties. The list array that I pass seems to have 0 elements in the controller. Can anyone assist me with this problem ...

Which is better for creating a gradual moving background: Javascript or CSS?

I'm attempting to discover how to create a background image that scrolls at a slower pace than the page contents. I'm currently unsure of how to achieve this effect. A great example of what I'm aiming for can be seen here Would this require ...

What is the best way to combine these two arrays in order to generate the desired JSON structure in a React

Is there a way to transform two arrays like these: const age = [31,53,62] const names = ['john', 'sam', 'kathy'] Into the structure shown below: const data = { "children": [ { "id": 1, "name": "john", "age ...

When using npm install, nested dependencies may not be installed automatically. However, you can explicitly install them to

In my custom package located at https://github.com/Voitanos/jest-preset-spfx, I have specified the following dependencies: "dependencies": { "@types/jest": "28.1.4", "identity-obj-proxy": "3.0.0", &qu ...

Having trouble adding/removing/toggling an element class within a Vue directive?

A successful demonstration can be found at: https://jsfiddle.net/hxyv40ra However, when attempting to incorporate this code within a Vue directive, the button event triggers and the console indicates that the class is removed, yet there is no visual chang ...

Is the normalizePort function in ExpressJS truly essential?

I recently implemented a new project using the express-generator. Within the file bin/www, there is a function called normalizePort: ... var http_port = 3000; var port = normalizePort(process.env.PORT || http_port); app.set('port', port); .. ...

An exception is thrown by TypeScript's readline.createInterface function

My current project involves creating an electron app. I am facing an issue in the main.ts file where I have constructed a seemingly simple class with a constructor that is not running as expected. The problem arises when the call to readline.createInterfac ...

I need assistance from someone knowledgeable in HTML and CSS. I am trying to create a div that dynamically increases its width until it reaches a specific

Seeking assistance to create a dynamic div that continuously expands its width until it reaches a maximum of 540px. It should start at 75px. Below is the HTML and CSS code I've attempted: .Loading-Screen { background-color: black; color: alicebl ...

Creating an AI adversary for a simple Tic Tac Toe game board: a step-by-step guide

Being new to programming, I recently completed a basic Tic Tac Toe gameboard successfully. However, as I progress to the next phase of my assignment which involves implementing an AI opponent, I encountered several challenges. As a novice in programming, ...

Having trouble with the production deployment of a Dockerized React application

As I work on containerizing my create-react-app for production using a Dockerfile and Docker-compose.yml, I am facing a challenge in creating the production build. The issue arises from the fact that the scripts required to run the build command are listed ...

Interactive MaterialTable editing with dropdown selection

I'm currently tackling the challenge of creating a MaterialTable that includes an inline editable field with a dropdown feature. The hurdle I am facing appears to lie within the columns object. By utilizing the lookup attribute, it is possible to defi ...

What is the best way to create shared scope and transmit data within an Angular directive?

In my angular directive, I have the following code: app.directive('myDir', function () { return { restrict: 'E', scope: true, template:'<div>{{myindex}}</div>', link: function(scope, element, att ...

elementToBeClickable is not supported by webdriverio

I am having some trouble with the 'waitForEnabled' function as it does not seem to behave like Webdriver's elementToBeClickable. Is there anyone who can provide some guidance on how to use this API effectively? ...

Retrieving information from a JSON object that includes arrays

I've been researching how to extract data from the response body of a server, but I haven't had much luck finding a solution that works for my https request returning a JSON object. //Initiate the request: request({ //Specify the request met ...

Activating Dynamic Functionality through JavaScript Input

I am currently working on a form in Apex 4.1 where I have an address lookup field that utilizes JavaScript to connect to an address database and populate separate fields with the address details (address1, address2, town, postcode). On the same page, I ha ...

How to display Autocomplete dropdown list in Material-UI only when user starts typing something?

Is there a way to make Material-UI's Autocomplete dropdown list appear only when the user starts typing? I've integrated the Material-UI Autocomplete component into my project, but I'm facing an issue where clicking on the TextField automati ...