The getStaticProps() method in NextJS does not get invoked when there is a change in

I have integrated my front-end web app with Contentful CMS to retrieve information about various products.

As part of my directory setup, the specific configuration is located at /pages/[category]/items/[id].

Within the /pages/[category] directory, you will find Index.tsx file containing the following code:

// Page component

interface ProductsIndexProps {
    products: ProductItemModel[],
    totalPages: number,
    currentPage: number
}

export default function ProductsIndex(props: ProductsIndexProps) {

    const { products, totalPages, currentPage } = props;

    const router = useRouter();

    return (
        <div>
            <div className={styles.title_section}>
                <h2 className={styles.title}>Results for all items</h2>
            </div>

            <div className={styles.list_container}>
                <section className={styles.list_sidebar}></section>
                <ProductList
                    products={products}
                    category={asString(router.query.category || "") || ""}
                    currentPage={currentPage}
                    totalPages={totalPages}
                />
            </div>
        </div>
    );
}

...
export const getStaticPaths: GetStaticPaths = async () => {

    return {
        paths: [
            { params: { category: "laptops" } },
            { params: { category: "motorcycle" } },
            { params: { category: "accessories" } },
        ],
        fallback: false,
    }
}

export const getStaticProps: GetStaticProps = async (context) => {

    const category = context.params?.category || "";
    const productsData = await getPaginatedProducts(1, category);
    const envPag = process.env.pagination || '0';
    const totalPages = Math.ceil(productsData.total / parseInt(envPag));

    return {
        props: {
            products: productsData.items,
            totalPages,
            currentPage: 1
        },
    }
}

My main objective is to dynamically fetch data from getPaginatedProducts based on the "category" parameter and display it on the corresponding [category].tsx page.

What I intend to achieve: When navigating to /laptops, getPaginatedProducts is invoked to retrieve laptops data. Similarly, when accessing /motorcycle, getPaginatedProducts is called to retrieve motorcycle data.

The issue at hand is that while the getPaginatedProducts function consistently returns data, Next.js's getStaticProps fails to update the data when the URL changes.

In essence, if I visit /laptops first, I receive the correct laptops data. However, upon subsequently navigating to /motorcycle, the content within [category].tsx still reflects the previous data (laptops). Only after refreshing the page does the data update correctly.

Is there a workaround or alternative solution to address this issue?

Answer №1

getStaticProps retrieves data during the build process, but if you need real-time data that changes frequently, it may not be suitable. The default setting of revalidate to false means that only cached data is displayed.

In this case, server-side rendering might be a better option for you. Check out this section on When should I use getServerSideProps? and also refer to this question.

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

Type inference in TypeScript with transitivity

Consider this code snippet for illustration: function foo(t: "number"): number function foo(t: "string"): string function foo(t: "boolean"): boolean function foo(t: "number" | "string ...

Invoke a function in Playwright exclusively when the test title includes a specific @tag

After years of utilizing Selenium, SpecFlow, NUnit, and other testing tools, I have recently delved into Playwright with TS. My goal is to interact with the AzureDevOps API to mark tests as automated only if they contain a specific tag in the test title (e ...

Incorporating numerous query parameters in Angular version 14

I am currently working on developing a multi-item filter feature for my application and I am faced with the challenge of sending multiple query parameters in the API request to retrieve filtered items. My main concern is whether there is a more efficient ...

Issue with Next.js 14's "Route interception" feature not functioning correctly when deployed in a production environment

Summary The "Intercepting routes" feature is functional locally (localhost:3000) However, the same feature does not work in production (website.com) Watch this video to see the issue The Issue I'm facing a problem with implementing a feature wher ...

What could be the reason behind my Vue file triggering a TS6504 error and suggesting to "allowJs"?

My Vue 3 project, which incorporates TypeScript, is encountering an issue when I attempt to execute vue-tsc --noEmit. error TS6504: File '/proj/src/pages/Index.vue.__VLS_template.jsx' is a JavaScript file. Did you mean to enable the 'allowJs ...

Shared validation between two input fields in Angular 2+

I have a unique task at hand. I am working on creating an input field with shared validation. The goal is to ensure that both fields are technically required, but if a user fills in their email address, then both fields become valid. Similarly, if they ent ...

Challenges with implementing TailwindCSS classes in a Next.js application

I've encountered some issues in my nextJS app with utilizing certain TailwindCSS classes such as top, left, or drop-shadow. Even after attempting to update Tailwind from version 1.9.5 to 3.3.3, I have not seen any changes. I believe that I am import ...

What is the list of status codes that Next.js returns when performing an SSR redirect?

Currently, I am utilizing the Next redirect object in my project to perform redirects within the getServerSideProps function. I am curious about what specific status code is sent back in the response. Upon reviewing the documentation, the only hint I came ...

Tips for parsing text responses in React to generate hyperlinks and emphasize specific words

I'm currently tackling a React project and facing an interesting challenge. I have a text response that needs to be parsed in a way that all URLs are automatically turned into clickable hyperlinks (using anchor tags). Moreover, there's a requirem ...

I am facing an issue with Recharts not occupying the full width in my Nextjs/Reactjs project. Despite setting it to 100% width, it does not behave as

I am currently working with Recharts in combination with Next.js and Tailwindcss. I decided to create my own barchart by copying a code snippet from Recharts, but encountered an issue where changing the height to aspect worked fine, however setting the wid ...

Exploring the capabilities of argon2-browser in a cutting-edge setup with vite

After spending several hours attempting to implement the argon2-browser library in a Vue app with Vite, I have been encountering a persistent error. Despite following the documentation closely, I keep receiving the following message: This require call is ...

Unlock the potential of Angular $http by leveraging TypeScript generics in your web development projects

I have been attempting to implement a generic promise return in my code: public getUserData: () => ng.IPromise <string> = () => { var promise = this.makeRequest<string>('http://someurl.com',null) .then((resp ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

The absence of "_ssgManifest.js" and "_buildManifest.js" files in a Next.js application deployed on Google Cloud Platform was discovered

Upon opening the website, there are instances where the console displays the following errors: GET https://example.com/subpath/_next/static/9ufj5kFJf/_buildManifest.js [HTTP/3 404 Not Found 311ms] GET https://example.com/subpath/_next/static/9ufj5kFJf/_ss ...

Running multiple instances of Chrome to execute all scenarios sequentially within a single feature file in Protractor

I need to run all scenarios in multiple instances of a browser. I've set the maximum instance value in capabilities, but only one instance of Chrome opens and the tests run sequentially. How can I ensure that the tests run in multiple instances simult ...

Performing a search through a string array and updating a specific portion of each string

I am faced with an array containing a long list of Strings, and my goal is to filter out all the strings that begin with 'INSERT ALL' and replace the number inside the parentheses with the string ' NULL' Here is the original array: le ...

Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like th ...

Angular Material's autocomplete feature allows users to easily search

I am currently working on creating an Angular Material Autocomplete feature. At the moment, I have successfully displayed the options and when selected, the correct name is inserted into the input field. However, my next task is to enable filtering of the ...

What is the best method for quickly filtering an array of objects according to the user's input?

What seemed like a simple task has me puzzled. I'm trying to sort through an array of objects based on user input. [{ name: Stan, age: 20, height: 190 }, { name: Pan, age: 30, height: 180 }, { name: Dan, age: 28, height: 185 }, { name: San, age: 20, ...

Generating Angular component based on selector

I developed an app that showcases various visualizations of RxJS operators such as rx-map, rx-filter, rx-reduce, and more. The visualizations function correctly on their own. Now, I am looking to enable users to select which visualization they want to view ...