The reliability of next router events can sometimes be called into question as they do not always function consistently

I've been working on creating a loading screen for my Next.js project. The issue I'm facing is that sometimes the loading message stays on the screen and doesn't go away even after the page has loaded. I suspect this may be due to the state not changing or the Router not checking the path properly after loading.

I attempted to pass a dependency array with the router, router.asPath, and router.events but the problem persists. How can I make the loading screen disappear once the page finishes loading?

import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/router';

export default function Loading() {
    const router = useRouter()
    const [loading, setLoading] = useState(false)

  useEffect(() => {
    const hanldeChangeStart = (url) => {
      url !== router.asPath && setLoading(true)
    }
    const hanldeChangeComplete = (url) => {
      url === router.asPath && setLoading(false)
    }
  
    router.events.on('routeChangeStart', hanldeChangeStart)
    router.events.on('routeChangeComplete', hanldeChangeComplete)
    router.events.on('routeChangeError', hanldeChangeComplete)
    
    return () => {
      router.events.off('routeChangeStart', hanldeChangeStart)
      router.events.off('routeChangeComplete', hanldeChangeComplete)
      router.events.off('routeChangeError', hanldeChangeComplete)
    }
  })

  if(loading){
    return (
        <div className='vh-100 vw-100 text-center'>
        <h1>Loading...</h1>
        <p>{loading ? 'loading' : 'notloading'}</p>
        </div>
    )
  } 
}

My app.js structure is as follows:

import Loading from '@/components/Loading';

export default function App({ Component, pageProps }) {
  
  
  return (
    <>
      <Loading />
      <Component {...pageProps} />
    </>
  )
}

Answer №1

I managed to resolve the issue by implementing a conditional statement in App.js. This way, the loading screen is only displayed when the page is still loading, and it gets replaced with the actual content once everything is loaded.


import Loading from '@/components/Loading';

export default function App({ Component, pageProps }) {

  return (
    <>
      {loading ? <Loading /> :
      <Component {...pageProps} />}
    </>
  )
}

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

Encountered an error message stating 'Unexpected Token <' while attempting to launch the node server

After adapting react-server-example (https://github.com/mhart/react-server-example), I encountered an issue with using JSX in my project. Despite making various changes like switching from Browserify to Webpack and installing babel-preset-react, I am still ...

I'm trying to establish a connection to MongoDB within the getStaticProps function in Next.js. Can anyone

Hello, I am a beginner in next.js and I have successfully rendered the home page on the server by populating the props object through a file named "products.json". Now, my next goal is to populate the props object in the function called getStaticProps usin ...

Accessing a model's field within an Ember.js each loop

Here is the code for a route that I am working on: Calendar.DateIndexRoute = Ember.Route.extend({ model: function(data) { return {arr:getCalendar(data), activeYear: data.year, activeMonthNumber: data.month, activeDay: data.da ...

Ways to access the scrollTop attribute during active user scrolling

I've been working on a website that utilizes AJAX to keep a chat section updated in real-time. One issue I encountered was ensuring the chat automatically scrolled to the bottom when a user sent a message, but remained scrollable while new messages we ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

What is the best way to print a canvas element once it has been modified?

My goal is to include a "Print Content" button on a webpage that will print a canvas element displaying workout metrics. However, the canvas content, which consists of a visual graph of workout data, changes based on the selected workout (bench, squat, etc ...

Getting a return value from a post request in NextJs 9 Serverless: a step-by-step guide

I am currently working on a serverless application using NextJs but I have hit a roadblock when trying to retrieve a user's JWT in the return value after making a post request to my database. While everything else seems to be functioning correctly, th ...

Internet Explorer versions 9 and 10 do not support the CSS property "pointer-events: none"

In Firefox, the CSS property pointer-events: none; functions properly. However, it does not work in Internet Explorer 9-10. Are there any alternative approaches to replicate the functionality of this property in IE? Any suggestions? ...

Create an input field with a dynamic and exclusive identifier using the DataTables plugin

I am having trouble creating unique IDs for each input field based on the number of rows Here is the code snippet: $(document).ready(function() { var oTable = $('#jsontable').dataTable(); //Initialize the datatable $.ajax({ url ...

Interactive table created with DataTables that automatically updates the dynamic JSON data source whenever changes are made to the table

Using the Datatables plugin, I am dynamically populating a table with HTML rendered from a JSON array. However, I need the table to update the model (datasource) stored client-side whenever an edit is made. When navigating to a new page on the table, it s ...

Issue with rendering HTML entities in Material UI when passing as props

Encountered a problem with the radio buttons in Material UI. Currently, Material UI accepts value as a prop for the FormControlLabel component. When passing a string with an HTML entity like below, it gets parsed correctly. <FormControlLabel value="fem ...

What is the process for configuring environmental variables within my client-side code?

Is there a reliable method to set a different key based on whether we are in development or production environments when working with client-side programs that lack an inherent runtime environment? Appreciate any suggestions! ...

Unable to include the variable "$localStorage"

While working on my method in app.js, I encountered the following error: Uncaught Error: [$injector:strictdi] function($rootScope, $q, $localStorage, $location) is not using explicit annotation and cannot be invoked in strict mode http://errors.angula ...

Utilize the fetch function to showcase information retrieved from a specific endpoint on a webpage using Javascript

Hey there, I have a Node server with an http://localhost:3000/community endpoint. When I make a GET request to this endpoint, it returns information about three different users in the form of JSON objects. [ { "avatar": "http://localhost:3000/avatars ...

When navigating to the next page, MUIDataTable displays a "no matching records exist" message for server-side pagination, despite the data being successfully returned in the network tab

In my next js app, I am utilizing MUIDatatable with server-side pagination. The issue I am facing is that even though the data is correctly returned by the API for each page change, it only displays on the first page. When I try to navigate to the next pag ...

Webpack Plugin System for Building Web Applications

In the context of my project, I am currently working on a product utilizing Symfony for the back-end and react/react-router for the front-end, all connected via Webpack. My plan is to structure my app into different "extensions", which would consist of a " ...

Having difficulty toggling a <div> element with jQuery

I am attempting to implement a button that toggles the visibility of a div containing replies to comments. My goal is to have the ability to hide and display the replies by clicking the button. The "show all replies" button should only appear if there are ...

What is the best way to direct to a different component while simultaneously replacing the current component?

Currently, I am developing a messaging application with ReactJS and MaterialUI for theming. In the interface, there is an Appbar and a permanent drawer already implemented. My goal now is to display the inbox, sent, and new message components in the remain ...

Encountering a 504 Timeout Error with Next.js and Next-Auth on our live server

After successfully developing a basic Next.js app with authentication using Next-Auth, I encountered a peculiar issue upon deployment to my production server. Despite configuring the environment variables accordingly in the .env.local file, I faced a persi ...

Error: Unable to authenticate due to timeout on outgoing request to Azure AD after 3500ms

Identifying the Problem I have implemented SSO Azure AD authentication in my application. It functions correctly when running locally at localhost:3000. However, upon deployment to a K8s cluster within the internal network of a private company, I encounte ...