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
Loading
component works when you navigate through pages.From the docs
if you navigate from a different page to
Home
page, you will see the loading componentIn 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