ShotaroHirose59 / nextjs-dashboard

Learn Next.js
https://nextjs-dashboard-dun-pi-28.vercel.app
0 stars 0 forks source link

Chapter7 Fetching Data #10

Open ShotaroHirose59 opened 3 months ago

ShotaroHirose59 commented 3 months ago

Now that you've created and seeded your database, let's discuss the different ways you can fetch data for your application, and build out your dashboard overview page. https://nextjs.org/learn/dashboard-app/fetching-data

Topics

ShotaroHirose59 commented 3 months ago

Choosing how to fetch data

API layer

next.jsではRoute HandlersでAPIを作れる

Database queries

React Server Componentsを使用する場合はAPIレイヤーをスキップして直接データベースにリクエストしてOK データベースの秘密をクライアントに公開されないため。 ↑これしっかり深ぼった方が良さそう。RSCのレンダリング、データフェッチの仕組みとか

ShotaroHirose59 commented 3 months ago

Using Server Components to fetch data

RSCでデータフェッチするメリットまとめ

ShotaroHirose59 commented 3 months ago

雑メモ

You could fetch all the invoices and sort through them using JavaScript. This isn't a problem as our data is small, but as your application grows, it can significantly increase the amount of data transferred on each request and the JavaScript required to sort through it.

ソートやフィルターはJSではなくバックエンド側でやりましょう

mapのindexを使ったclsxの条件文。テクい

{latestInvoices.map((invoice, i) => {
            return (
              <div
                key={invoice.id}
                className={clsx(
                  'flex flex-row items-center justify-between py-4',
                  {
                    'border-t': i !== 0,
                  },
                )}
              >

Again, you might be tempted to fetch all the invoices and customers, and use JavaScript to manipulate the data. For example, you could use Array.length to get the total number of invoices and customers:

But with SQL, you can fetch only the data you need. It's a little longer than using Array.length, but it means less data needs to be transferred during the request. This is the SQL alternative:

総数系もlength使うんじゃなくてバックエンドで用意してもらうのが良いのか。Array.lengthよりは大変だが。 徹底してクライアント側のJSを減らそうという意図が伝わる

ShotaroHirose59 commented 3 months ago

What are request waterfalls?

「ウォーターフォール」とは、前のリクエストの完了に依存する一連のネットワーク リクエストを指します。データフェッチの場合、各リクエストは、前のリクエストがデータを返した後にのみ開始できます。

次のリクエストを行う前に条件を満たしたいためにウォーターフォールが必要な場合もある(ex: 最初にユーザーの ID とプロファイル情報を取得したい場合があります。ID を取得したら、友達のリストを取得します。) この場合は各リクエストは前のリクエストから返されたデータに依存しているので。

--> 次のリクエストが前のリクエストに依存しているならOK

この仕様はパフォーマンスに影響を与える可能性があるので注意が必要。

Parallel data fetching

並行データフェッチができる Promise.all() or Promise.allSettled() どんなライブラリやフレームワークにも適用できるネイティブのJavaScriptパターンが良いそう。

However, there is one disadvantage of relying only on this JavaScript pattern: what happens if one data request is slower than all the others?

--> 並行データフェッチもフェッチの完了は全てのフェッチが終わってからなので。