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.

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.

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

What is preventing me from accessing a JavaScript object property when using a reactive statement in Svelte 3?

Recently, while working on a project with Svelte 3, I encountered this interesting piece of code: REPL: <script lang="ts"> const players = { men: { john: "high", bob: "low", }, }; // const pl ...

Using Angular to create a dynamic form with looping inputs that reactively responds to user

I need to implement reactive form validation for a form that has dynamic inputs created through looping data: This is what my form builder setup would be like : constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...

Implement handleTextChange into React Native Elements custom search bar component

I need help with passing the handleTextChange function in the SearchBarCustom component. When I try to remove onChangeText={setValue} and add onchange={handleTextChange}, I am unable to type anything in the search bar. How can I successfully pass in the ...

Is NATS.io compatible with React Native?

Struggling with integrating nats.io into a React Native project using Typescript has presented many challenges. Is there a way to successfully incorporate it without having to modify node_modules of nats (such as changing the "fs" import to "react-native-f ...

Using fast refresh in Next.js is leading to a fetch error when integrated with Express.js

When trying to fetch data from my API, I encountered an error due to fast refresh in Next.js. It seems that req.params only work once because of a bug with Next.js's fast refresh feature. Do you know of any solutions or alternative ways to retrieve th ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

Loading an external javascript file dynamically within an Angular component

Currently, I'm in the process of developing an Angular application with Angular 4 and CLI. One of my challenges is integrating the SkyScanner search widget into a specific component. For reference, you can check out this Skyscanner Widget Example. T ...

Encountered an issue while attempting to integrate Nebular into my Angular application

As a newcomer to Angular, I decided to try installing Nebular using the command ng add @nebular/theme. However, I encountered an error in the process. Upon entering the command into my terminal, the following error message appeared: ? Which Nebular theme ...

"Alert: Cautionary notification when utilizing server action in the latest version of Next.js

I keep receiving this warning message in my server-side console while using server actions: Warning: Cannot specify an encType or method for a form that specifies a function as the action. React provides those automatically and they will be overridden. Ho ...

Inserting a pause between a trio of separate phrases

I am dealing with three string variables that are stacked on top of each other without any spacing. Is there a way to add something similar to a tag in the ts file instead of the template? Alternatively, can I input multiple values into my angular compo ...

Sentry alert: Encountered a TypeError with the message "The function (0 , i.baggageHeaderToDynamicSamplingContext) does not

My website, which is built using Next.js and has Sentry attached to it, runs smoothly on localhost, dev, and staging environments. However, I am facing an issue when trying to run it on my main production server. The error message displayed is as follows: ...

How can I send a large data object to a different page using dynamic routing in Next.js without using query parameters?

When working on a page, I retrieve data and loop through it. Within my mapping function, I render a card component with specific data: pokemonsList?.map((pokemon, index) => { return ( <Link href={`/pokemon/${pokemon ...

Discovering a specific string within an array of nested objects

Seeking guidance on creating a dynamic menu of teams using JavaScript/TypeScript and unsure about the approach to take. Here is an example dataset: const data = [ { 'name': 'Alex A', 'agentId': '1225& ...

Inquiring about the versatility of NextJS Stripe Elements for various scenarios

Currently, I am in the process of developing an online store using NextJS (Typescript) and Stripe. Everything has been going smoothly so far except for one issue... The problem arises from having my entire application wrapped within an Elements component: ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

WebSocket connection outbound from Docker container fails to establish

Running a TypeScript program on Docker that needs to open a Websocket connection to an external server can be a bit tricky. Here is the scenario: ----------------------- ------------------------------ | My Local Docker | ...

Having trouble getting a Custom React Component from an external library to work with MUI styling

I am currently working with a React component that comes from a module located in the node_modules folder: type Props = { someProps: any }; export function ComponentA(props: Props) { const [value, setValue] = React.useState(""); return ( <Te ...

Setting up NextJS on Vercel for website deployment can encounter a common error known as ENOENT Error, which is caused by the absence of a specific file or

Everything works perfectly on my local machine: import fs from 'fs' import path from 'path' export default function createNewDirectory (tokenSignature: string) { const directoryPath = path.join(process.cwd(), 'notes', to ...

When using a function as a prop in a React component with Typescript generics, the type of the argument becomes unknown

React version 15 or 18. Typescript version 4.9.5. When only providing the argument for getData without using it, a generic check error occurs; The first MyComponent is correct as the argument of getData is empty; The second MyComponent is incorrect as t ...