The Challenge of Refreshing Static Site Generation in NextJS Version 13

I've encountered a problem with updating data on a basic data page. The situation is simple: there's a page that shows category data and another page that allows editing of the same data. After making edits and returning to the list page, I expect the list to reflect the changes. However, since it's a Static Site Generation (SSG) page, it generates static data at build time.

import prismadb from "@/lib/prismadb";
import CategoriesClient from "./components/client";

export const dynamic = "force-dynamic";

export default async function Categories(res) {
  let categories;
  categories = await prismadb.category.findMany({
    orderBy: {
      createdAt: "desc",
    },
  });

  const formattedCategories = categories.map((category) => ({
    id: category.id,
    name: category.name,
    isActive: category.isActive,
  }));

  return (
    <>
      <CategoriesClient data={formattedCategories} />
    </>
  );
}
  async function onSubmit(data) {
    try {
      setLoading(true);
      if (initialData) {
        await axios.patch(`/api/categories/${params.categoryId}`, data);
      } else {
        await axios.post(`/api/categories`, data);
      }
      router.refresh();
      router.push(`/categories`);
      toast.success(successMessage);
    } catch (err) {
      toast.error(`An error as occurred: ${err.response.data}`);
    } finally {
      setLoading(false);
    }
  }

I have attempted using the revalidate property on the list page, but it only works with a hard refresh, not with the router which I am currently using.

export const revalidate = 1;

At present, I'm utilizing force-dynamic to make the page dynamic. However, when I navigate to the page through the router or Next.js Link, everything functions correctly. Yet, when I manually refresh the page with F5 or input the link directly, I encounter a 500 error (only in the production environment on Netlify, local machine works fine).

Is there a solution to ensure that the page updates accurately in all scenarios, including manual refreshes?

I would greatly appreciate any assistance with this issue as I have been struggling with it for days.

Answer №1

One key advantage of Static site generation is its speed, as it provides a pre-built page for immediate display to the client upon request. Additionally, next/router avoids hard reloads to maintain the properties of a single-page application.

To address this issue, there are two potential solutions: 1- Stick with static site generation but update the client-side code to trigger a revalidation for the page using a revalidation API instead of the revalidate key. An example implementation:

export default async function handler(req, res) {
  // Verify the secret token for authentication
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' })
  }
 
  try {
    await res.revalidate('/path-to-revalidate') // Update with actual path
    return res.json({ revalidated: true })
  } catch (err) {
    return res.status(500).send('Error revalidating')
  }
}

Invoke this API whenever changes impact the page and refer to the full documentation here. In the client-side, utilize the useEffect hook to call the data API within an empty dependency array for router refresh.

2- If modifications occur frequently, consider utilizing server-side rendering over static generation.

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

There seems to be an issue with AppModule in your code. The error message states that it is not recognized as an NgModule and the problem

After upgrading to node 6, angular 4, typescript 2.3.2, and @angular/cli 1.02, I meticulously followed the steps outlined in the Guide for updating @angular/cli. I will include my entire package.json below in case there are any relevant details. The specif ...

Error in setting cookies using Javascript document.cookie on iOS with cordova-plugin-ionic-webview

Backend-sent cookies are successfully stored, but the app itself cannot set cookies. When running the code snippet below: document.cookie = "notified=1; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"; console.log(document.cookie); An empty strin ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...

What could be causing my function to not register with my EventListener?

I'm attempting to perform an action when I click on an element. I have added an eventListener to change the value of a variable upon clicking on that element. However, the eventListener is not working as expected. When I debug the code, it seems like ...

Does a document.onmodification event exist, or something similar?

Is there a specific event in JavaScript that triggers whenever an element is added, removed, or modified? Although lacking in detail, it is a straightforward question. ...

Building module dependencies in the Dojo dojo

I'm in the process of utilizing the Dojo builder to compile a unified file that encompasses all the necessary modules for my application, excluding the application itself. Below is an illustration of a layer definition: layers: { 'dojo/dojo ...

You cannot convert a function to a string while utilizing axios get in nuxtServerInit

While attempting to connect my app to the backend using Udemy's Nuxt.js course, I encountered a GET http://localhost:3000/ 500 (Internal Server Error) on the client side with the following code: import Vuex from 'vuex'; import axios from &a ...

Authentication through Auth0 login

After successfully registering a user in Auth0 for login purposes (found in the Users section of the dashboard), I implemented the following code to authenticate the user using an HTML form with username and password fields: public login(username: string, ...

Mix up table data cells using Javascript/jQuery

Can anyone provide me with some helpful tips? I'm really struggling with this. My Objective I aim to create a table with two columns ("name" and "rating"), consisting of 5 rows. 2 of these rows should have a random "rating" between 6-10 2 other ro ...

react state change not triggering re-render of paragraph

I recently started learning react and web development. To streamline my work, I've been using ChatGPT, but I'm facing an issue that I can't seem to solve. I'm trying to fetch movie descriptions from the TMDB API using movie IDs, but des ...

Enhancing functionality by updating a function to accept an object as input instead of individual key:value pairs in TypeScript

I'm currently tackling a challenge with a friend's icon library component, specifically with their set() function. The issue arises when I want to invoke two functions, namely setRandomColor() and setColor(), both intended to update two values w ...

There was a Runtime Error that occurred, stating a TypeError: It is not possible to access properties of an undefined value (specifically

I've encountered an issue with a donut chart implemented from react-apex charts. Every time I try to render the page containing the chart, an error occurs. However, if I make changes to a property of the chart, it renders without any errors on the fro ...

Scraping JavaScript Content Webpages with VBA

I'm attempting to extract a table from the Drainage Services Department website. I've written the VBA code below, but it doesn't seem to be working. I suspect that the issue lies in the fact that this particular table is generated using Java ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

Challenge with Merging Bootstrap Clean Blog Template with React Application

I am facing difficulties while trying to merge the Bootstrap Clean Blog Template (Link Attached) into my React App. This template is available for free. After downloading the template, I created a new react project and moved all static assets & files ...

Ways to verify whether an array contains any of the specified objects and then store all those objects in Supabase

Perhaps the title of my question is not very clear, but I find it difficult to summarize in just one line. To provide context, it would be best to see the JavaScript query I'm making for Supabase and its response. The data: [ { title: 'Th ...

Retrieve a string value in Next.JS without using quotation marks

Using .send rather than .json solved the problem, thank you I have an API in next.js and I need a response without Quote Marks. Currently, the response in the browser includes "value", but I only want value. This is my current endpoint: export ...

Issue with displaying dates correctly when retrieving data from an external CSV using Highcharts (Highstock)

I have been struggling for several days to integrate Highstock with an external CSV file. Initially, the problem was that the imported data was sorted in "descending" order while Highcharts required it to be sorted in "ascending" order. After discovering a ...

how to name a collection variable in MongoDB shell using JavaScript

When using the mongo shell with JavaScript, is it possible to dynamically set the collection name in order to work with multiple collections? db.collection.insert() ...

NavLinkButton - add style when active or selected

I'm working with a list of NavLinks: const users = Array.from(Array(5).keys()).map((key) => ({ id: key, name: `User ${key}`, })); <List> {users.map((user) => { return ( <ListItem disablePadding key={user.id}> ...