Looking to create dynamic pages on NextJS without relying on fixed paths?

I am looking to create a unique user experience by offering discounts on my website based on the users' citizenship ID numbers. By using their ID number, I can customize the discount amount according to factors such as location, age, and gender.

Users can navigate to mywebsite.com/megadiscount where they can enter their ID number in a form to discover their personalized discount. Additionally, I want them to have the option to visit mywebsite.com/megadiscount/[id number] for the same information.

In order to achieve this with NextJS, I understand that I need to create both megadiscount/index.js and megadiscount/[id].js to handle the ID parameter in the URL.

The challenge arises when dealing with the getStaticPaths function in the megadiscount/[id].js file, as I am unsure of all the possible ID values that will be generated.

This is how my megadiscount/[id].js file is structured:

const Page = ({discount}) => {
  return (
    <>
      <h1>You are eligible for a {discount}% discount!</h1>
    </>
  )
}

export async function getStaticPaths() {

  return {
    paths: [], // Unable to anticipate all potential ID values here
    fallback: false,
  };
}

export async function getStaticProps(context) {
  const { slug = "" } = context.params;
  const discount = fetchDiscountFromServer(slug)
  return {
    props: {
      discount
    },
  };
}

export default Page;

Answer №1

export default function DisplayDiscount({ discount }) {
  return (
    <>
      <h1>You qualify for a discount of : {discount}%</h1>
    </>
  );
}

export async function fetchDiscount({ params: { id } }) {
  //Retrieve the discount based on the provided id
  const discount = await retrieveDiscountFromServer(id);
  return {
    props: { discount },
  };
}
export async function determineStaticPaths() {
  return {
    paths: [],
    fallback: "blocking",
  };
}

NextJS introduces fallback:"blocking" handling mechanism for scenarios such as this. Take a look at the documentation

However, considering server-side rendering (SSR) might be more suitable in this context. Static pages would be generated for each user, which is acceptable. Yet, if the discount information changes frequently, adjusting the revalidate:1 option with lower values may help to keep it relatively updated although not in real-time.

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

Leveraging useContext to alter the state of a React component

import { createContext, useState } from "react"; import React from "react"; import axios from "axios"; import { useContext } from "react"; import { useState } from "react"; import PermIdentityOutlinedIcon f ...

Utilize a JSON file to generate a network visualization using the vis.js library

I am currently working with vis.js to generate a visualization. In the example code, I am using the file saveAndLoad.html. The save function works well as it allows me to export a json file. However, I am encountering an issue when trying to load the jso ...

The quirks of JSON.stringify's behavior

I am in the process of gathering values to send back to an ASP.NET MVC controller action. Despite using JSON.stringify, I keep encountering Invalid JSON primitive exceptions and I am unsure why. I have a search value container named searchValues. When I i ...

How can we detect line breaks within a selection using JavaScript?

Apologies for the lack of expertise in the content below, as it is being produced by a designer experimenting with coding :D The goal here is to determine the number of lines selected or highlighted by the cursor. When I mention "lines," I mean what is vi ...

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...

The onScroll event is failing to trigger when scrolling to a particular div on Next.js

Is there a way to fetch data when a specific div comes into view on a SSR page in Next.js? I attempted using the onScroll event on the div, but it doesn't seem to be triggering. Any suggestions? function handleScroll() { console.log("scrolled ...

Utilizing Material UI's (MUI) date picker in conjunction with react-hook-form offers a

I'm currently developing a form with a date field utilizing MUI and react-hook-form for validation. I have experimented with two different methods of rendering the field, but when I try to submit the form, the expected value is not being returned: Me ...

Ways to correct inverted text in live syntax highlighting using javascript

My coding script has a highlighting feature for keywords, but unfortunately, it is causing some unwanted effects like reversing and mixing up the text. I am seeking assistance to fix this issue, whether it be by un-reversing the text, moving the cursor to ...

Exciting news ahead with swr, "Make sure to have fallback data ready when utilizing suspense in SSR."

I am attempting to incorporate React Suspense into a Next.js project My application is set up for client-side rendering only, without server-side rendering While Suspense is functioning properly, I have encountered the following error: Fallback data is ...

Implementing Javascript to insert IFRAME into the DOM

I'm looking to incorporate an iframe into my webpage. The iframe needs to link to a specific URL. I attempted to add the following code to my HTML, but it's not functioning as expected: document.createElement('<iframe src='http://ex ...

AngularJS is not triggering the $watch function

I'm facing an issue with the $scope.$watch function, as it's not being triggered when expected. In my HTML document, I have a paginator using bootstrap UI: <pagination total-items="paginatorTotalItems" items-per-page="paginatorItemsPerPage" ...

What is the best way to create a unique custom control in Javascript, potentially utilizing jQuery?

My goal is to develop a custom control using JavaScript that includes methods, properties, and events, and can be rendered within a div element. For example, one such control could be a calendar. It would display in a div, with customizable properties for ...

Enhance the HTML content using a JavaScript function

Here is the code that I have: <label>Brand</label></br> <select name="brand" id="brand" onChange="changecat(this.value);"> <option value="" selected>Select Brand</option> <option value="A">AMD</option&g ...

Retrieving information from Flask server using an Ajax request

Exploring Flask and Ajax, my server-side web application is meant to double and return a passed number. I adapted the code from the example on Flask's site, resulting in this Python snippet: from flask import Flask, request, jsonify # Initialize the ...

Custom providers do not override Angular UrlResolver

In my Angular application, I am trying to implement a custom UrlResolver provider to incorporate cache breaking logic. I came across this question on Stack Overflow: . Unfortunately, it seems that overriding the default compiler UrlResolver using a provid ...

Neither Output nor EventEmitter are transmitting data

I am struggling to pass data from my child component to my parent component using the Output() and EventEmitter methods. Despite the fact that the emitter function in the child component is being called, it seems like no data is actually being sent through ...

Unable to provide any input while utilizing npm prompts

After installing npm prompts, I encountered a strange issue. When trying to run the example code for npm prompts, I found that I couldn't enter any input at all. The underscore in the input field would blink for a few seconds, then the cursor would ju ...

Creating a flexible parent tag for grouping child elements using Angular 2

My Objective I am determined to develop an Angular 2 button component that can dynamically render as either an <a /> tag or an <input /> tag based on the value of a property called type. Furthermore, this button component should be able to acc ...

The program failed to run properly because it couldn't find the reference to Chart

I added chart.js to my project using npm with the command: npm install chart.js --save-dev. In the file "resources/assets/js/bootstrap.js", I included it by using: require('chart.js');. After running npm run dev in the console, it compiled succe ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...