0

I'm trying to build a simple app with Nextjs 13.4.9, and there's this weird behaviour I'm facing among loading.tsx files while navigating between routes. It seems like when I navigate to a route which has a corresponding loading.tsx file, instead of imidiately showing the corresponding loading.tsx file from the route segment, for a split second it shows the loading.tsx file from its parent route.

  • app
    • products
      • laptop
        • page.tsx
        • loading.tsx
      • smart-watch
        • page.tsx
        • loading.tsx
      • page.tsx
      • loading.tsx

So basically in a routing structure like above, when I navigate between /products/smart-watch and /products/laptop, for a brief moment is shows the loading.tsx file from products and then it switches to the loading.tsx file from the route I'm trying to visit. My code is as simple as it gets and they're all Server Components. has anybody faced something like this ? Is it a bug or am I just missing something ?

I'd appreciate any help. Thanks

1 Answers1

0

U can add 'layout.tsx' in child folder, ie can help load 'loading.tsx' from parent folder.


folder structure

  • app
    • laptop
      • layout.tsx
      • loading.tsx
      • page.tsx
    • smart-watch
      • layout.tsx
      • loading.tsx
      • page.tsx
    • header.tsx
    • loading.tsx

app/products/page.tsx

const Page = async () => {

    // wait 3 second
    async function taketime () {
        await new Promise((resolve) => { 
        setTimeout(resolve,3000);
        });
    }
    await taketime();

    return (
        <>
            <p>Product Home Page.</p>
        </>
    );
}

export default Page;

app/prodcuts/laptop/layout.tsx

interface LayoutProps {
    children: () => void;
}

const Layout = async ({children}:LayoutProps) => {

    // Wait 3 secound
    async function taketime () {
        await new Promise((resolve) => { 
        setTimeout(resolve,3000);
        });
    }
    await taketime();

    return (
        <>
            {children}
        </>
    )
}

export default Layout;

app/products/laptop/page.tsx

import { Header } from "../header";

const Page = async () => {

    // wait 6 second
    async function taketime () {
        await new Promise((resolve) => { 
        setTimeout(resolve,6000);
        });
    }
    await taketime();

    return (
        <>
            <Header/>
            <p>Product - Laptop Details.</p>
        </>
    );
}

export default Page;
Masunulla
  • 55
  • 3
  • I just tried your solution, but unfortunately the glitch still remains. The problem is not that the individual loading.tsx files don't load at all, the problem is the the parent loading.tsx file flashes for a moment before the correct loading.tsx file show up. – Mister Killuminati Aug 25 '23 at 02:01