Challenges with implementing Typescript in Next.js and the getStaticProps function

Having trouble with the implementation of getStaticProps where the result can be null or some data. The typings in getStaticProps are causing issues, even after trying conditional props. Any suggestions?

type ProductType = {
     props:
         | {
             product: null;
             page: string,
             status: number
          }
        | {
            product: Product;
          }
 }



function ProductPage(props: ProductType): Children  {
  const { product, status, page } = props; // errors here
  if (!product) {
    return (
      <ErrorPage statusCode={status} page={page}  />
    )
  }

  return (
    <ProductPage { ...props } />
  )
}


export default ProductPage;



interface StaticParams extends ParsedUrlQuery {
  id: string
}

type StaticProps = {
  props: {
      product: ProductType;
    }
}
// Getting a lengthy error message from "StaticProps".
// Unable to handle either "error" values or valid data.
export const getStaticProps: GetStaticProps<StaticProps, StaticParams> = async (context) => {
  const params = context.params!

  const response = await fetch(`${process.env.NEXT_PUBLIC_HOST}/products/${params.id}`);
  const product = await response.json();


  if (!product || product.errors) {
    return {
      props: {
        product: null,
        page: 'error page',
        status: 404
      }
    }
  }


  return {
    props: {
      product: { ...product },
    },
    revalidate: 10
  }
}

Answer №1

It seems like there might be some confusion with how your ProductType is nested within your StaticProps. The current definition of your StaticProps appears to be:

type StaticProps = {
  props: {
    product: {
      props:
        | {
            product: null
            page: string
            status: number
          }
        | {
            product: Product
          }
    }
  }
}

To resolve the compiler error, you should ensure that the first return statement in your getStaticProps function aligns with the structure of the StaticProps:

return {
  props: {
    product: {
      props: {
        product: null,
        page: 'error page',
        status: 404,
      },
    },
  },
}

While this may address the compilation issue, it's advisable to revisit the definition of the StaticProps type. Additionally, ensure that the response from your /products/{productId} endpoint adheres to the StaticProps type to prevent potential runtime errors that TypeScript may not catch.

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

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Is it common for pdf parsing libraries pdf2json and pdf-parse to encounter compatibility issues with the Next JS app router?

I've run into some challenges while trying to incorporate PDF parsing functionality into my Next JS application. It seems that the libraries pdf2json and pdf-parse are not compatible with the new Next JS app router. To replicate the issue, follow the ...

Encountering an issue: Issue arises when attempting to update Next.js from version 7 to version 9.3, displaying an error message

Encountered this error after upgrading an existing functioning application to NextJs: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to expor ...

Setting cookies through the `Set-Cookie` Header does not work in Chrome

Encountering difficulties setting a cookie through Express.JS in my frontend (Next.JS). The Headers received from the API (/login): Access-Control-Allow-Origin: * Connection: keep-alive Content-Length: 354 Content-Type: application/json; charset=utf-8 Dat ...

What is the best way to generate a dummy ExecutionContext for testing the CanActivate function in unit testing?

In my authGuard service, I have a canActivate function with the following signature: export interface ExecutionContext extends ArgumentsHost { /** * Returns the *type* of the controller class which the current handler belongs to. */ get ...

Encountering a 401 Error while using Laravel Sanctum/Airlock

Currently, I am utilizing Laravel as the back-end for my innovative Next JS application, with Sanctum being leveraged for authentication purposes. While session authentication operates smoothly on the front end, issues arise when attempting to send reque ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

Handling HTTP Errors in Angular Components with NGRX

I have successfully integrated the store into my angular project. I am able to handle and process the successSelector, but I am facing difficulty in capturing any data with the errorSelector when an HTTP error occurs from the backend. The error is being c ...

Best practice for organizing initializer code in Next.js

I am currently developing a NextJS app alongside NX app that utilizes firestore as the backend. Within my setup, I have set up api routes and implemented a library for managing feature-based functionalities, such as: initFirebaseAdmin export const initFi ...

Utilizing TypeScript for various return types with the same parameters

Exploring TypeScript Signatures In an effort to embrace TypeScript fully, I am implementing strongly typed signatures in my Components and Services, including custom validation functions for angular2 forms. I have discovered that while function overloadi ...

TypeScript purity - "The variable exports is not defined"

I encountered an issue with my simple client-server TypeScript application where every import statement in my client.ts file triggers a ReferenceError: exports is not defined error in the browser after loading the HTML. Here is the project structure: root ...

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...

Using Next.js in conjunction with Tailwind CSS and the shadcn/ui library to tackle the issue of preventing overscroll from creating

As I delve into a Next.js project, my goal is to use Tailwind CSS to craft an interface featuring a sidebar on the left, a header at the top, and a main content area. However, an issue has surfaced where users can over-scroll, leading to a blank space appe ...

When you use array[index] in a Reduce function, the error message "Property 'value' is not defined in type 'A| B| C|D'" might be displayed

Recently, I delved deep into TypeScript and faced a challenge while utilizing Promise.allSettled. My objective is to concurrently fetch multiple weather data components (such as hourly forecast, daily forecast, air pollution, UV index, and current weather ...

Leveraging onClick for router.push to extract information and refresh the content in Next.js

As a newcomer to React, I am facing a challenge with executing a GraphQL query to update the data on a page based on the link clicked by the user (look for two onClicks in the code snippet below). After the user clicks a link, handleSubmit should also upd ...

What is the best way to refresh a navigation bar after making an API request, such as when using Google Sign-In?

Struggling to grasp the hook concept in this particular scenario: The flow goes like this - the user logs in with Google, which updates the session state. Consequently, the visitorType state transitions from 'viewer' to 'buyside'... A ...

The MUI component received props that were not defined

I created a customized MUI card with the intention of applying a dark background when the darkBg prop is passed. However, I've encountered an issue where despite passing darkBg as true, the card's background remains white. To troubleshoot, I atte ...

RXJS: Introducing a functionality in Observable for deferred execution of a function upon subscription

Implementing a Custom Function in Observable for Subscribers (defer) I have created an Observable using event streams, specifically Bluetooth notifications. My goal is to execute a function (startNotifictions) only when the Observable has a subscriber. ...

Automatically redirect users to a new page using ReactJs/NextJS after a brief delay of 5 seconds

After a customer logs in, I want to show them a welcome page that automatically redirects them to another page after 5 seconds. To achieve this, I initially set the state with a default value of 5 seconds and then used setInterval to count down by 1 every ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...