skip to Main Content

I’m having trouble implementing a loading component in Next.js v13. According to the documentation, I created a loading.tsx file in my src directory, but it’s not being displayed. I’ve also included a function to fetch data. However, every time I refresh the page, it directly shows the API response from the server without displaying the loading component. Could anyone suggest how to rectify this? Additionally, is there any further configuration required to display the loading component?

Here is my code:

In page.tsx:

import { IResult } from '@/interface';
import Results from '@/components/Results';

const API_KEY = process.env.API_KEY

export default async function Home({ searchParams } : {searchParams: any}) {
  const genre = searchParams.genre || 'fetchTrending';
  const res = await fetch(`https://api.themoviedb.org/3/${genre === 'fetchTopRated'
    ? 'movie/top_rated' :
      'trending/all/week'
  }?api_key=${API_KEY}&language=en-US&page=1`, { next: {revalidate: 100000 }})

  if (!res.ok) {
    throw new Error('Failed to fetch data')
  }

  const data = await res.json()

  const results = data.results as IResult[]

  console.log({results})
  return (
    <>
      <main className="flex min-h-screen flex-col items-center justify-between p-4">
        <Results results={results}></Results>
      </main>
    </>
  )
}

And in loading.tsx:

import React from 'react'

export default function Loading() {
  return (
    <div>loading...</div>
  )
}

I would greatly appreciate any help or suggestions. Thank you!

2

Answers


  1. Loading component works when you navigate through pages.

    From the docs

    An instant loading state is fallback UI that is shown immediately upon
    navigation. You can pre-render loading indicators such as skeletons
    and spinners, or a small but meaningful part of future screens such as
    a cover photo, title, etc. This helps users understand the app is
    responding and provides a better user experience.

    if you navigate from a different page to Home page, you will see the loading component

    Login or Signup to reply.
  2. In NextJS 13, instead of adding loading.tsx and page.tsx in src you are supposed to add these files in app, if you are using src then src/app/…

    For example if you want to create home route then your file structure would look like:
    src/app/home/page.tsx
    src/app/home/loading.tsx

    You don’t need any extra configuration for this

    For reference – Nextjs loading docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search