Issue arises in Nextjs14 when utilizing <Link> to navigate to the same page, resulting in Loading.tsx malfunction

In my Next.js project using version 14.2.7, the root page is a server component that retrieves a ticket from a server action.

import { uniqueRandom } from "lodash";
import Link from "next/link";

const getTicket = () => new Promise<number>((resolve) => {
  const generatedTicket = uniqueRandom(1, 10000);
  setTimeout(() => resolve(generatedTicket), 2000);
})

export default async function Home() {

  const newTicket = await getTicket(); // Retrieves a new ticket from server action

  return (
    <>
      <h1>Your new ticket number is: {newTicket}</h1>
      <Link href={`/?q=${newTicket}`}>Get another ticket</Link>
    </>
  );
}

This represents the loading page:

export default async function Loading() {
    return (
        <h1 className="loader">
            LOADING...
        </h1>
    )
}

The loading page displays when clicking the refresh button in the browser. However, it does not work when clicking the 'Get another ticket' link as the page gets blocked for 2 seconds until the new ticket is generated.

Have I misunderstood how to use the loading page? Are there any specific configurations or coding considerations needed in this case? Thank you!

Answer №1

If your Loading element is not loading automatically, you can implement the use of Suspense and set it as a fallback to display while waiting for the resolution of newTicket.

import { random } from "lodash";
import Link from "next/link";
import { Loading } from "<proper path>";
import { Suspense } from "react";

const getTicket = () => new Promise<number>((r) => {
  const ret = random(1, 10000);
  setTimeout(() => r(ret), 2000)
})
export default async function Home() {

  const newTicket = await getTicket(); // Retrieve a new ticket from server action

  return (
    <>
    <Suspense fallback={<Loading />}>
      <h1>Your new ticket is: {newTicket}</h1>
      <Link href={`/?q=${newTicket}`}>Get a new ticket</Link>
    </>
  );
}

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

Displaying a dynamic list of components in NextJS: A step-by-step guide

On my website homepage, I am working on creating a list of decks categorized by each category. Here's how it looks: Category A: Deck 1 | Deck 2 | Deck 3 Category B: Deck 4 | Deck 6 Category C: Deck 7 I have figured out how to fetch all the cate ...

How to invoke a method in a nested Angular 2 component

Previous solutions to my issue are outdated. I have a header component import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { Observable } from 'rxjs/Observable'; ...

Sending Information to Routes - Error: No Routes Found to Match

I recently tried implementing a solution from an article () to pass an ID between modules in order to use it as a search filter. However, I encountered the "cannot match any routes" error and have been struggling for some time since I'm new to Angular ...

Issue encountered in Loopback 4: Error with @repository dependency injection (TypeError: Undefined property 'findOne')

As I set up Bearer Token authentication for my Loopback 4 application, I referenced this implementation guide: https://github.com/strongloop/loopback-next/tree/master/packages/authentication. Within my src/providers/auth-strategy.provider.ts file, I encou ...

I am interested in using a loop in Angular to highlight my div element

Enhancing my comprehension regarding the mentioned images. If I don't select anything within the div property, the default style (css) should appear like this, at least when one div is selected. However, the issue arises when unable to select. This ...

Use the .map method to transform JSON data retrieved from Prisma within

Trying to work with mapping a JSON object in a Next.js class component using data from Prisma. I've had to stringify the data from Prisma to avoid a serialization error on the date parameter. I know I can't directly use .map on this.props.commen ...

When refreshing the page, redux-persist clears the state

I have integrated redux-persist into my Next.js project. The issue I am facing is that the state is getting saved in localStorage when the store is updated, but it gets reset every time the page changes. I suspect the problem lies within one of the reducer ...

To properly display a URL on a webpage using Angular, it is necessary to decode

After my console.log in Angular 5 service call to the component, I can see the correct data URL being displayed http://localhost:4200/inquiry?UserID=645 However, when it is inside an Angular for loop in the HTML template, it displays http://localhost:42 ...

Discord.js experiences limitations with storing multiple data in conjunction with TypeScript when using MySQL

Question Currently, I am developing a Discord bot to track messages using typescript and discord.js. I have included my code below. The issue I am facing is that the data is not being saved correctly. Each time a user sends messages, their message count i ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...

Angular: define an object with multiple nested levels using variables for keys and values

I am working on a React form where I have an array of objects for each field component. My goal is to compile these objects into one object containing all the form values. interface FormProps { name: string; subName?: string; value: undefined | strin ...

The namespace does not have any exported object named 'LocationState'

I encountered the following issue while attempting to execute my TypeScript application: Namespace '"C:/DevTools/git/motor.ui/node_modules/history/index"' has no exported member 'LocationState'. Here is a snippet from my pack ...

Angular 12 Directive causing NG-SELECT disabled feature to malfunction

Looking for a way to disable ng-select using a directive. Does anyone have any suggestions on how to accomplish this? Here is the code I have been working with, along with an example that I was trying to implement. setTimeout(() => { const selectElem ...

In Angular, you can achieve two-way binding between a mat tab group and an array in your typescript file. But what's the best way to programmatically switch to a specific mat-tab using types

Check out the code snippet below. I have a mat tab group with a mat tab corresponding to each ValidationStep object in the validationSteps[] array in my TypeScript file through two-way binding. Whenever I add a new element to the array, a new tab is dynam ...

Error: The datasource URL provided must use the prisma:// protocol

I have been working on developing a Next.js application. The app functions as expected when run locally in both development and production modes, using data from the cloud. However, when I deploy the app on Vercel and try to interact with my database, I en ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...

Having trouble deciphering the Enum definition in the Typescript Build

One of my projects utilizes a typescript package stored in npm with all the necessary definitions: index.d.ts export declare namespace OfferCraft { enum Country { es, it, fr, uk, de } enum Brand { ...

What is the method for obtaining class constructor argument types in the form of an object?

Let's consider an example where we have a class called Summator: export default class Summator { constructor(private readonly firstArgument: number, private readonly secondArgument: number) {} get sum() { return this.firstArgument + this.s ...

Guide to retrieve API data from Axios within the getServerSideProps method in NextJS?

I'm currently developing an App using Next.js and I am facing a challenge with connecting to specific API routes (established with API Platform) in order to populate pages with the responses from those routes. Although the API is functioning properly ...

Alert: Issue with data transmission. TypeError reported: Unable to modify property query of #<IncomingMessage> which is restricted to read-only access

Introduction: I have been following a tutorial on YouTube titled Build a Complete Digital Marketplace with Next.js 14, React, tRPC, Tailwind using Payload CMS for the admin dashboard. I meticulously followed each step in the video and ensured that the so ...