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

Intellisense missing in VSCode for Angular and typings

Attempting to start a new project using Angular 1.5.5 and looking to incorporate TypeScript into my coding process within Visual Studio Code. I have included the necessary typings for Angular in my project: typings install angular --save --ambient I&ap ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

Optimizing Nginx for caching server-side rendered (SSR) web pages developed using React and Next.js

After creating an application where some pages are rendered on the server side, I noticed that something wasn't right. When viewing the requested pages in my browser, everything seemed normal. However, when I sent a CURL request to the page and saved ...

Leveraging the power of both TypeScript 2.3 and 2.4 concurrently within Visual Studio 2015.3 on a single machine

Can TS 2.3 and TS 2.4 be used on the same machine simultaneously? For example, I have one project in VS 2015.3 compiling with TS 2.3 and another project compiling with the latest TypeScript version (TS 2.4). I recently installed TypeScript 2.4, which aut ...

Dynamic Material UI Timeline

I am facing a challenge with making the Timeline in Material UI responsive for the first time. Currently, I have it set to align 'alternate', but I want it to switch to align 'left' when viewed on mobile or certain screen widths. I have ...

The current Angular 11 build seems to lack in producing sufficient Lazy chunk files

Currently, I am working on implementing lazy loading for modules from different libraries in my project. This involves utilizing two libraries located in the node_modules directory, which are then lazily loaded by the main application. Below is a snippet o ...

establishing the default value as p-multiselect

Here is the code snippet I am currently working on: export class LkBoardStatus { id : number = 0; descr : string = ''; } In the component.ts file, I have defined the following: //... lkBoardStatusList: LkBoardStatus[] = []; selectedStat ...

There are no imports in index.js and there is no systemjs configuration set up

After creating a fresh Angular project using ng new some-name, I noticed that the generated index.html file does not include any <script> tags and there is no SystemJS configuration either. Is this the expected behavior? I was anticipating the CLI ...

What is the Angular2 equivalent of the AngularJS $routeChangeStart event?

During our time working with AngularJS, we utilized the $routeChangeStart/End event in the $rootScope to monitor changes in the route object. What is the equivalent method for monitoring route changes in Angular2? How can we achieve the same functionality ...

Enabling non-declarative namespaces in React using Typescript: A beginner's guide

I'm diving into the React environment integrated with Typescript, but I still have some confusion about its inner workings. I really hope to receive thorough answers that don't skip any important details. I came across a solution that involves d ...

You are unable to apply 'use client' on a layout element in Next.js

While attempting to retrieve the current page from the layout.txt file, I encountered errors after adding 'use client' at the top of the page: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data parseMod ...

Redirect pages that do not match a specific regular expression to a different backend in NextJS

I need to integrate a NextJS application with a Laravel project. The NextJS app handles specific routes: / /node/123456789 /way/123456789 /relation/123456789 /install Where 123456789 represents any numbers. All other URLs should be managed by the Larave ...

How to display two elements side by side within a div using React

I have an array that looks like this: const arr = [1,2,3,4,5,6,7,8,9,10] I am looking to display the elements in pairs per line within two-dimensional divs. Here is what I have in mind: This represents the main React element: render() { return <di ...

Facing a challenge with handling HTTP data in a TypeScript-based Angular web application

I am currently working on developing a web application using Angular and the SpringMVC Framework. One of the tasks I'm facing is loading a list of users (referred to as "consulenti" in the code). While the backend HTTP request works fine, I encounter ...

Getting dynamic variables in the `getStaticProps` function of NextJS can greatly enhance

I am working on utilizing getStaticProps in order to fetch data based on a variable. Here is a sample code snippet: export async function getStaticProps() { const res = await fetch(localWordpressUrl, { method: 'POST', headers: { 'C ...

Is it possible to assign an object literal to a typed variable in TypeScript? Can you also specify the typeof object literal?

Consider a scenario where you have the following type definition: type MyType = { A: number | string } If you try to assign a value like this, TypeScript will correctly flag it as an error: const myValue1: MyType = { A: 123, B: "Oh!", // This wil ...

Distribute among an array of specific types

I am trying to achieve this behavior using Typescript: type animals = 'cat' | 'dog' let selectedAnimals: animals[] = ['cat'] selectedAnimals = [ // <- Type 'string[]' is not assignable to type 'animals[]&ap ...

Is TypeScript being converted to JavaScript with both files in the same directory?

As I begin my journey with TypeScript in my new Angular project, I find myself pondering the best approach for organizing all these JS and TS files. Currently, it appears that the transpiler is placing the .js files in the same directory as the correspondi ...

When running the test, the message "Unable to resolve all parameters for BackendService" is displayed

Upon executing the ng test command, the following error was displayed. This is my service specification: describe('BackendService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { p ...

What is causing the Next.js build to attempt connecting to the database?

In my server page in Next.js 14, I am using App Router to fetch data from a database. The connection pool for the database is created at lib/db.js import mysql from "mysql2/promise"; import * as schema from "@/schema"; const pool = m ...