ページを作成する
page.tsx
を以下のように作成します。
page.tsx
async function getData() {
const res = await fetch('https://api.example.com/...')
return res.json()
}
export default async function Page() {
const data = await getData()
if (!data) {
notFound()
}
return <main></main>
}
ロード画面を作成する
pages.tsx
と同じ階層にloading.tsx
を作成します。
loading.tsx
export default function Loading() {
return <p>Loading...</p>
}
上記のように記述するとpage.tsx
のgetData()
の処理が完了するまでpage.tsx
の代わりにloading.tsx
が表示されるようになります。
特定のコンポーネントのみローディング状態を表示させたい場合には以下のように<Suspense></Suspense>
で括ります。
page.tsx
import { Suspense } from 'react'
import { PostFeed, Weather } from './Components'
export default function Page() {
return (
<section>
<Suspense fallback={<p>Loading feed...</p>}>
<PostFeed />
</Suspense>
<Suspense fallback={<p>Loading weather...</p>}>
<Weather />
</Suspense>
</section>
)
}