The getStaticProps() function in NextJS has not been invoked

Currently, I am working on a basic website and my goal is to retrieve data from an API and showcase it on my component. However, I've encountered an issue where the getStaticProps() method doesn't seem to be triggering.

Below is the code snippet of the component in question :

import React from "react";
import {GetStaticProps, InferGetStaticPropsType} from "next";

type RawProject = {
    owner: string;
    repo: string;
    link: string;
    description: string;
    language: string;
    stars: number;
    forks: number;
}

function Projects({projects}: InferGetStaticPropsType<typeof getStaticProps>) {
    console.log(projects);
    return (
        <section id="projects" className="bg-white p-6 lg:p-20">
            <h1 className="sm:text-4xl text-2xl font-medium title-font mb-4 text-gray-900 pb-6 text-center">
                Quelques de mes projets
            </h1>
            {/*
            <div className="container px-5 mx-auto">
                <div className="flex flex-wrap">
                    {rawProjects.map((project: RawProject) => (
                        <ProjectCard
                            title={project.repo}
                            language={project.language}
                            description={project.description}
                            imageUrl="https://dummyimage.com/720x400"
                            repoUrl={project.link}
                        />
                    ))}
                </div>
            </div>
            */}
        </section>
    );
}

export const getStaticProps: GetStaticProps = async () => {
    console.log("getStaticProps()");
    const res = await fetch("https://gh-pinned-repos-5l2i19um3.vercel.app/?username=ythepaut");
    const projects: RawProject[] = await res.json();
    return !projects ? {notFound: true} : {
        props: {projects: projects},
        revalidate: 3600
    };
}

export default Projects;

To view the complete code, please visit : https://github.com/ythepaut/webpage/tree/project-section

I am uncertain whether the issue stems from using TypeScript or implementing a custom _app.tsx.

I have explored potential solutions from :

However, none of them have resolved the issue for me. Any assistance would be greatly appreciated. Thank you in advance.

Answer №1

getStaticProps() function is restricted to pages in Next.js.

The current code you have:

import Hero from "../sections/Hero";
import Contact from "../sections/Contact";
import Projects from "../sections/Projects"; // It's not allowed to call getStaticProps() in this component

function HomePage(): JSX.Element {
    return (
        <div className="bg-gray-50">
            <Hero />
            <Projects />
            <Contact />
        </div>
    );
}

export default HomePage;

Instead, you should call getStaticProps() inside index.tsx and pass the props to the component like this ::

import Hero from "../sections/Hero";
import Contact from "../sections/Contact";
import Projects from "../sections/Projects";

function HomePage({data}): JSX.Element {
    return (
        <div className="bg-gray-50">
            <Hero />
            <Projects data={data} />
            <Contact />
        </div>
    );
}

export const getStaticProps: GetStaticProps = async () => {
    console.log("getStaticProps()");
    const res = await fetch("https://gh-pinned-repos-5l2i19um3.vercel.app/?username=ythepaut");
    const projects: RawProject[] = await res.json();
    return !projects ? {notFound: true} : {
        props: {projects: projects},
        revalidate: 3600
    };
}
export default HomePage;

Answer №2

In NextJs, data fetching methods like getStaticProps only run on the server, making them exclusive to pages and not regular React components.

For more information, please refer to their documentation.

If you need data fetching in Normal Components, you can utilize client-side rendering. NextJS recommends using the SWR library found here.

As per their documentation:

SWR is a strategy that initially retrieves data from cache (stale), then sends the fetch request (revalidate), ultimately providing up-to-date information.

Answer №3

In Next.js, the functions getInitialProps, getServerSideProps, and getStaticProps can only be used in pages

Upon reviewing your project, I noticed that your Project.tsx file was located in a component folder instead of the necessary pages folder for these functions to function properly.

https://i.sstatic.net/V0OWe.png

Answer №4

When working with the pages folder, don't forget to export getStaticProps as well

For example:

export { default } from '../../games/tebak-kata/game';
export { getStaticPaths } from '../../games/tebak-kata/game';
export { getStaticProps } from '../../games/tebak-kata/game';

Answer №5

My encounter with poor service worker implementation resulted in a similarly negative experience. If you discover that it functions properly after performing an "Empty Cache and Hard Reload," then it's advisable to review your service-worker code and ensure that you are not caching any unnecessary pages. https://i.sstatic.net/vlNKg.png

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

The error message "Unable to access property 'open' of an undefined menu" is being displayed in a TypeScript code

I am facing an issue with the action in my menu. For this project, I am using a material menu and icons. The main menu code appears as follows: <mat-menu #rootMenu="matMenu" [overlapTrigger]="false"> <ng-template matMenuContent let-element="ele ...

Tips for building and implementing Angular URL Parameters for URLs in the form: "component/#/?id=..."

I am currently facing a situation where I have an application with an existing user base. I am looking to avoid disrupting their current links for a smoother transition. However, the previous links are in this format: (server)/viewer/#/?id=12. Please see t ...

What sets apart using (@Inject(Http) http: Http) from not using it?

Following a recent query, I now have a new question. What sets apart these two approaches? Here is the original code I used: import {Http, HTTP_PROVIDERS} from 'angular2/http'; @Component({ viewProviders: [HTTP_PROVIDERS], ..// constructor(h ...

Exploring the Depths of Observables in Angular2 Guards

I have a Guardian overseeing a specific route. Within the canActivate method, I am trying to perform two HTTP requests, with the second request being dependent on the response of the first one. However, it seems like the second request is not being trigger ...

Displaying nested web service array data in Angular 4

I created a project that retrieves data from a web service API. However, the API contains nested arrays that also need to be displayed. How can I access the data from these nested JSON arrays? What is the correct way to extract this data within the HTML co ...

Fixing the "Cannot find name" error by targeting ES6 in the tsconfig.json file

I recently started learning AngularJS through a tutorial. The code repository for the tutorial can be accessed at this link. However, upon running npm start using the exact code provided in the tutorial, I encountered the following error: Various TS2304 e ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

The server has access to an environment variable that is not available on the client, despite being properly prefixed

In my project, I have a file named .env.local that contains three variables: NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=pk_test_<get-your-own> MAGIC_SECRET_KEY=sk_test_<get-your-own> TOKEN_SECRET=some-secret These variables are printed out in the file ...

Ways to resolve NPM dependency conflicts

Attempting to set up all the necessary npm packages for the AWS sample demo found at https://github.com/aws-samples/amazon-chime-sdk-classroom-demo on my laptop has been a bit challenging. Every time I try to run npm install I can't help but wonder i ...

Using `location.reload()` and `location.replace(url)` does not seem to function properly when using Electron with Angular

Using Electron to rebuild a pre-existing web app, the main.js file in electron is kept simple: // Modules to control application life and create native browser window const {app, BrowserWindow} = require('electron') // Keep a global reference o ...

How can I integrate Ollama server with Nextjs?

I am currently working on a project that involves setting up the Ollama server with LLMs like Mistral and Llama2, along with a Next.js server to interact with it. This project is aimed at helping me learn more about Docker, but I've run into a problem ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...

Combining certain key values from two dictionaries based on matching IDs in Angular

I am currently working with two arrays of JSON objects in Angular. Both dictionaries have a key-value pair called "song_id" in common. My goal is to combine the "rating" key-value from the second array into the first array where the song_id matches. Array ...

Experiencing unexpected behavior with Next.JS getStaticProps functionality

I am currently working on a website where I want to display dynamic feedback as cards. However, my fetchData variable within the Home function is always returning undefined. Here's the code snippet I have tried: import UserCard from "../component ...

Troubleshooting: Issue with Next Js dynamic imports not functioning without SSR

I've run into an issue while trying to implement the react-carousel-3d library found at https://github.com/suhailsulu/react-carousel-3d. Unfortunately, it seems that the library does not currently support Server-Side Rendering (SSR), resulting in the ...

Determine parameter types and return values by analyzing the generic interface

I am currently working on a feature where I need to create a function that takes an interface as input and automatically determines the return types based on the 'key' provided in the options object passed to the function. Here is an example of ...

Encountering a Next.js 404 Error while trying to access a dynamic route despite having the correct

I am experiencing a 404 error (This page could not be found.) when attempting to access a dynamic route in my current Next.js project. The specific URL is http://localhost:3000/blog/id, and I have already updated to the latest version of Next.js. Here is ...

Firebase: Issue encountered during project deployment

My latest project utilizes Firebase as the main platform. While I have successfully used Firebase hosting multiple times without any issues, I am currently facing a new challenge. The project is built using Next.js version 14.2.3, but Firebase is prompting ...

ridiculing callback within parameter

I have a model setup in the following way: export class MyClass { grpcClient: MyGRPCClient; constructor(config: MyGRPCClientConfig) { this.grpcClient = new MyGRPCClient( config.serverUrl, grpc.credentials.createInsecure(), ); ...

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...