phymooc / learn-react

0 stars 0 forks source link

Next.js Data Fetching #6

Open phymo opened 1 month ago

phymo commented 1 month ago

fetch data on server

with fetch

// app/page.tsx
async function getData() {
  const res = await fetch('https://api.example.com/...')
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data')
  }

  return res.json()
}

export default async function Page() {
  const data = await getData()

  return <main></main>
}

how to cache and revalidate data

with 3rd party libraries

phymo commented 1 month ago

fetch data on client

with Route handler

with 3rd party library

phymo commented 1 month ago

Server Actions & Mutations

Convention use server

how to invoke

phymo commented 1 month ago

Best Practices

Fetch data on the server (recommended)

Fetch data where needed: no worrying about the performance implications of making multiple requests for the same data. because of react cache

streaming: (loading ui & streaming & suspense) allow you to progressively render and incrementally stream rendered units of the UI to the client.

sequential data fetching(waterfall): one depending on another

parallel data fetching:

preloading data: Using React cache, server-only, and the Preload Pattern

prevent sensitive data exposed to client: taintObjectReference and taintUniqueValue:

    // next.config.js
    module.exports = {
      experimental: {
        taint: true,
      },
    }
// app/utils.ts
import { queryDataFromDB } from './api'
import {
  experimental_taintObjectReference,
  experimental_taintUniqueValue,
} from 'react'

export async function getUserData() {
  const data = await queryDataFromDB()
  experimental_taintObjectReference(
    'Do not pass the whole user object to the client',
    data
  )
  experimental_taintUniqueValue(
    "Do not pass the user's address to the client",
    data,
    data.address
  )
  return data
}