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

MUI Grid with Custom Responsive Ordering

Can I achieve a responsive grid layout like this example? Check out the image here I have already coded the desktop version of the grid: <Grid container spacing={2}> <Grid item sm={12} lg={6} order={{ sm: 2, lg: 1 }}> ...

Using Arrow Functions in Angular 2 Typescript with Support for IE11

Are arrow functions in Typescript for Angular2 compatible with IE 11? I have come across information stating that arrow functions in javascript may not be supported in IE 11, but I am uncertain if the same applies to Typescript. ...

Disarrayed generic parameters in TypeScript

The title of the question may not be perfect, but it's the best I could do. Imagine a scenario where there is a function that accepts a callback along with an optional array. The callback takes an index and another optional array as parameters, and t ...

How to dynamically add an HTML element following a specific div class in Typescript and Angular

Is there a way to dynamically insert a component into a div after a specific element with a designated class name using TypeScript? <div class ="{{order.orderId}}"> <div class="enter-here"></div> <other html elements here> < ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

cycle through options of radio buttons

How can I display items of radio buttons, with the values of these items coming from a backend api? <div class="input-group col-md-9 input-group-sm"> <label>gender</label> </div> <!-- TO CORRECT ...

The Battle of Extends and Intersection in Typescript

Typescript's concept of extension is akin to C++'s inheritance. Intersection in Typescript involves creating a new object with all the properties from the intersected classes. Why utilize intersection when extends keyword can already merge ...

Creating a flexible route path with additional query parameters

I am facing a challenge in creating a unique URL, similar to this format: http://localhost:3000/boarding-school/delhi-ncr However, when using router.push(), the dynamic URL is being duplicated like so: http://localhost:3000/boarding-school/boarding-school ...

Unable to transform undefined or null into an object within Next.js

Hi there! Currently, I am working on creating a login page using Next.js and next-auth. I have included the necessary providers in the providers array within [...nextauth].js. However, when I attempt to run the following code: import { getProviders, signIn ...

What could be the reason for the variable's type being undefined in typescript?

After declaring the data type of a variable in TypeScript and checking its type, it may show as undefined if not initialized. For example: var a:number; console.log(a); However, if you initialize the variable with some data, then the type will be display ...

Guide on effectively converting a table of tuples to an array of objects utility function (similar to zip) while preventing the merging of all values in typescript version 5.2.2

Almost there, but stuck on the final TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol compiler error. Here's a nifty utility function called rowsToObjects() that many developers have probably come up with at some point, ...

Activate a spinner when a button is clicked within a row of an antd table

I created a table with a column that includes a button like the one below: const columns = [ ... { title: "button", dataIndex: "key", render: (text, record) => { return ( <Button icon={<Del ...

The infinite scroll feature is not functioning properly with the combination of get static props and GraphQL

I've been working on a project involving pokeapi graphql, and I developed an infinite scroll component that dynamically loads more pokemon as you scroll down the page. My goal was to preload the first 48 pokemons using static generation. Here's ...

Differences in the rendering of SVG feDiffuseLighting between Chrome and Firefox

Hey there! I encountered a strange issue with my next.js project. It has a default config and includes an SVG filter. <svg xmlns="http://www.w3.org/2000/svg"> <filter id='roughpaper'> <feTurbulence type=" ...

Importing BrowserAnimationsModule in the core module may lead to dysfunctional behavior

When restructuring a larger app, I divided it into modules such as feature modules, core module, and shared module. Utilizing Angular Material required me to import BrowserAnimationsModule, which I initially placed in the Shared Module. Everything function ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

What is the best way to ensure that Interface (or type) Properties always begin with a particular character?

I attempted to tackle this assignment using template literals, but unfortunately, I wasn't successful. Here is the interface that I am working with: interface SomeInterface { '@prop1': string; '@prop2': string; '@ ...

Combining 2 lists in Angular Firebase: A Simple Guide

I have been searching for a solution for the past 2 hours, but unfortunately haven't found one yet. Although I have experience working with both SQL and NoSQL databases, this particular issue is new to me. My problem is quite straightforward: I have t ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

I am looking to extract solely the numerical values

Programming Tools ・ react ・ typescript ・ yarn I am trying to extract only numbers using the match method But I keep encountering an error Error Message: TypeError: Cannot read property 'match' of undefined const age="19 years ...