2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Next.js】ロード画面を表示する方法

Posted at

ページを作成する

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.tsxgetData()の処理が完了するまで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>
  )
}

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?