Error: Trying to access the 'blogpost' property of an undefined variable results in a TypeError while executing the NPM RUN BUILD command in Next.js

Encountering a frustrating issue while trying to run my Next.js application for production build. The problem seems to be related to the "blogpost" parameter in the following codeblock:

import React from "react";
import Slab from "../../component/Slab/Slab";
import styles from "../../styles/slug.module.css"
import { GraphQLClient, gql } from "graphql-request";
import { RichText } from '@graphcms/rich-text-react-renderer';

const graphcms = new GraphQLClient(
  " https... ",
);

const QUERY = gql` 
  query Blogpost($slug: String!) {
  blogpost(where: {slug: $slug}) {
    title
    publishedAt
    synopsis
    post {
      raw
    }
  }
}
`;

const SLUGLIST = gql`
    {
    blogposts {
      slug
    }
  }
  
`;

export async function getStaticPaths() {
  const { blogposts } = await graphcms.request(SLUGLIST);
  return {
    paths: blogposts.map((blog: { slug: any; }) => ({ params: { slug: blog.slug } })),
    fallback: true,
  }
}

export async function getStaticProps({ params }:any) {
  const slug = params.slug;
  const blogData = await graphcms.request(QUERY, { slug });
  return {

    props: {
      blogpost: blogData,
    },
    revalidate: 10,

  };
}

export default function blogsSingle({ blogpost }:any) {
  console.log(blogpost)
  return (
    <Slab>
      <div className={styles.blogcontainer}>
        <div className={styles.latestblog}>
          <br />
          <article>
            <h1>{blogpost.blogpost.title}</h1> 
          </article>
        </div>
      </div>
    </Slab>
  );
};

Despite working fine in NPM RUN DEV mode, I encounter an error when trying NPM RUN BUILD or attempting deployment on Vercel.

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

If "blogpost" was undefined, why wouldn't it also throw an error during RUN DEV? Seeking assistance as I navigate through JavaScript, Next.js, and TypeScript, facing some roadblocks along the way. For those curious about the console log output of 'blogpost':

{ blogpost: { title: 'QRD...', publishedAt: '2022-12-10T03:37:42.781869+00:00', synopsis: 'My introduction.', post: { raw: [Object] } } }

Attempted solutions include:

  1. Reordering queries in the return(), which yields mixed results with undefined issues during build most of the time.
  2. Using "blogpost.blogpost" property in the return(), as it displays the GraphQL query correctly during development - akin to extracting children in any GraphQL query.

"blogpost param > blogpost type > then you can get to the rest of the children."

  1. Verified Hygraph API fields presence, confirmed successful API call logging in CLI/Dev Console.

  2. Avoiding an 'if' statement workaround since these variables should be defined without needing such measures.

  3. Identifying this specific file as the culprit, as removing the return() allows for successful deployment.

The expectation is that what works in development mode should seamlessly transition to build mode, potentially missing a simple detail. Any guidance would be greatly appreciated.

Answer №1

Aha! I finally figured it out. The issue was with how I defined the paths for my blog posts.

Originally, I had:

paths: blogposts.map((blog: { slug: any; }) => ({ params: { slug: blog.slug } })),

But then I realized that a simpler syntax would work better:

paths: blogposts.map(({slug}:any) => ({ params: { slug } })),

It turns out that by mapping just the slug, I am able to pass it as a parameter without any issues. This change has made a big difference in how Dev and Prod/Build/Export functions seamlessly together.

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

An effective method to utilize .map and .reduce for object manipulation resulting in a newly modified map

Here's an example of what the object looks like: informations = { addresses: { 0: {phone: 0}, 1: {phone: 1}, 2: {phone: 2}, 3: {phone: 3}, 4: {phone: 4}, 5: {phone: 5}, }, names: { 0 ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Enhanced VS code typings for Nuxt injected properties

My approach to injecting properties into the Nuxt TS context is as follows: ~/plugins/services.ts import Vue from 'vue'; import { errorService } from '~/services/error'; import { Plugin } from '@nuxt/types' const services: Pl ...

Is the use of "as" necessary in NextJS dynamic routing?

Is it necessary to use the as attribute along with the href attribute in both links, or can we just use the href? import Link from 'next/link' export default function () { return (<> <Link href="/someroute"> < ...

Angular Pipe: Working with Data Structures in Angular With Nested Arrays and Objects

After struggling to customize answers for similar questions, I find myself in need of some assistance. My current challenge involves using an angular pipe to filter the following data structure: subjects = [ { name: "subject1", keywords:[& ...

SSR Function Performs Properly in Mozilla Browser, But Faces Issues in Chrome

I'm encountering a problem with my Next.js project that involves server-side rendering (SSR). The issue arises when I have a payment flow in my application where users are directed to a bank page for payment. After returning to my page, I depend on an ...

Tips for accessing the 'index' variable in *ngFor directive and making modifications (restriction on deleting only one item at a time from a list)

Here is the code snippet I'm working with: HTML: <ion-item-sliding *ngFor="let object of objectList; let idx = index"> <ion-item> <ion-input type="text" text-left [(ngModel)]="objectList[idx].name" placeholder="Nam ...

Encountering challenges with reusing modules in Angular2

I am currently working on an angular2 website with a root module and a sub level module. However, I have noticed that whatever modules I include in the root module must also be re-included in the sub level module, making them not truly reusable. This is w ...

Can the server be used to conditionally control the isAmp function?

UPDATE: I need to clarify my question as it seems unclear. My goal is to pass the 'isAmp' variable from getInitialProps to the component in order to determine whether it should be an amp or regular page. Why do I want to do this? Because I want ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

How do I set up a Webpack loader in Next.js to handle SVGR files alongside the default image loader?

Currently, I am working with Nextjs 14.x and its Webpack bundler. My usual approach is to import SVGs as components by using @svgr/webpack. In my configuration within next.config.js, it looks like this: config.module.rules.push({ test: /\.svg$/, ...

Extract the content of a nested JSON object in ReactJS using map function

I am encountering an issue while attempting to map nested JSON data, specifically the error 'Element implicitly has an 'any' type'. The problem arises within the search component at: Object.keys(skills[keyName]).map() Below is the cod ...

Performing API requests in NextJS using Prisma on a client-side page

Currently, I am faced with a challenge in fetching data from my database on a NextJS page designated as a client page using "use client" as required by the theme I am working with. At the moment, I have a page that fetches data from the database and redire ...

The data type 'AbstractControl | null' cannot be assigned to type 'FormGroup'

I am facing an issue with passing the [formGroup] to child components in Angular. The error message says Type 'AbstractControl | null' is not assignable to type 'FormGroup'. I have double-checked my conditions and initialization, but I ...

Exploring the Wonders of React Memo

I recently started delving into the world of React. One interesting observation I've made is that when interacting with componentized buttons, clicking on one button triggers a re-render of all button components, as well as the parent component. impo ...

Experiencing an issue when attempting to deploy Strapi CMS with TypeScript on Railway - encountering the error message: "Unable to locate module 'typescript'"

Issue with Deploying Strapi CMS in TypeScript to Railway Currently facing challenges while trying to deploy Strapi CMS written in TypeScript to Railway. Despite the availability of a JavaScript template, there's a lack of a specific TypeScript templa ...

What is the process for including response headers to NextJS public assets?

How can I set the max-age response header for images and fonts in my NextJS project? I came across this documentation on NextJS, but as I am using next-compose-plugins, it's not very clear to me how to implement this in my current code. https://next ...

Exporting multiple sheets using Angular's ngx-export-as functionality

Currently utilizing ngx-export-as in my Angular project and I am looking to export an Excel file with multiple sheets. How can I achieve this export functionality? I have raised a concern regarding this on GitHub. ...

Obtain a controller's reference from a callback by utilizing TypeScript

Implementing a simple controller that utilizes a directive/component and passes a function as binding. However, when the function is called, there is no reference available to access any of the controller class services. Within the "public onTileClicked" ...

In the past, it was impossible to access all properties simultaneously from a TypeScript union

Recently, I purchased an online course that I had put off watching until now. In the course, it specifically mentioned that certain code in TypeScript was not allowed: type Name = { name: string } type Age = { age: number } type UnionBoth = Name | Age co ...