Skip to content

Commit

Permalink
Migrate latest changes
Browse files Browse the repository at this point in the history
  • Loading branch information
delbaoliveira committed Jun 7, 2023
1 parent d5467ab commit d8a9b5b
Show file tree
Hide file tree
Showing 14 changed files with 528 additions and 52 deletions.
2 changes: 1 addition & 1 deletion docs/01-getting-started/03-react-essentials.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ With Server Components, the initial page load is faster, and the client-side Jav

When a route is loaded with Next.js, the initial HTML is rendered on the server. This HTML is then **progressively enhanced** in the browser, allowing the client to take over the application and add interactivity, by asynchronously loading the Next.js and React client-side runtime.

To make the transition to Server Components easier, all components inside the [App Router](/docs/app/building-your-application/routing#the-app-directory) are Server Components by default, including [special files](/docs/app/building-your-application/routing#file-conventions) and [colocated components](/docs/app/building-your-application/routing#colocation). This allows you to automatically adopt them with no extra work, and achieve great performance out of the box. You can also optionally opt-in to Client Components using the ['use client' directive](#the-use-client-directive).
To make the transition to Server Components easier, all components inside the [App Router](/docs/app/building-your-application/routing#the-app-router) are Server Components by default, including [special files](/docs/app/building-your-application/routing#file-conventions) and [colocated components](/docs/app/building-your-application/routing#colocation). This allows you to automatically adopt them with no extra work, and achieve great performance out of the box. You can also optionally opt-in to Client Components using the ['use client' directive](#the-use-client-directive).

## Client Components

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ First, you will see these terms being used throughout the documentation. Here's
- **URL Segment:** Part of the URL path delimited by slashes.
- **URL Path:** Part of the URL that comes after the domain (composed of segments).

## The `app` Directory
## The `app` Router

In version 13, Next.js introduced a new **App Router** built on [React Server Components](/docs/getting-started/react-essentials#server-components), which supports shared layouts, nested routing, loading states, error handling, and more.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,15 @@ nav_title: Fetching
description: Learn how to fetch data in your Next.js application.
---

> **Good to know**:
>
> - This new data fetching model is currently being developed by the React team. We recommend reading the [support for promises React RFC](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md) which introduces `async` and `await` in Server Components and a new `use()` hook for Client Components.
> - While you can try it out, it is not yet stable. We'll keep these docs updated to reflect the latest developments.
The Next.js App Router allows you to fetch data directly in your React components by marking the function as `async` and using `await` for the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

React and Next.js 13 introduced a new way to fetch and manage data in your application. The new data fetching system works in the `app` directory and is built on top of the [`fetch()` Web API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
Data fetching is built on top of the [`fetch()` Web API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and React Server Components. When using `fetch()`, requests are [automatically deduped](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping) by default.

`fetch()` is a Web API used to fetch remote resources that **returns a promise**. React extends `fetch` to provide [automatic request deduping](/docs/app/building-your-application/data-fetching#automatic-fetch-request-deduping), and Next.js extends the `fetch` options object to allow each request to set its own [caching and revalidating](/docs/app/building-your-application/data-fetching/caching).
Next.js extends the `fetch` options object to allow each request to set its own [caching and revalidating](/docs/app/building-your-application/data-fetching/caching).

## `async` and `await` in Server Components

With the [proposed React RFC](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md), you can use `async` and `await` to fetch data in Server Components.
You can use `async` and `await` to fetch data in Server Components.

```tsx filename="app/page.tsx" switcher
async function getData() {
Expand Down Expand Up @@ -61,11 +58,9 @@ export default async function Page() {
}
```

> **Async Server Component TypeScript Error**
> **Good to know:**
>
> - An `async` Server Components will cause a `'Promise<Element>' is not a valid JSX element` type error where it is used.
> - This is a known issue with TypeScript and is being worked on upstream.
> - As a temporary workaround, you can add `{/* @ts-expect-error Async Server Component */}` above the component to disable type checking for it.
> To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher.
### Server Component Functions

Expand Down Expand Up @@ -100,7 +95,9 @@ fetch('https://...', { next: { revalidate: 10 } })

See [Revalidating Data](/docs/app/building-your-application/data-fetching/revalidating) for more information.

> **NOTE:** Caching at the fetch level via `revalidate` or `cache: 'force-cache'` stores the data across requests in a shared cache. You should avoid using it for user-specific data (i.e. requests that derive data from `cookies()` or `headers()`)
> **Good to know:**
>
> Caching at the fetch level with `revalidate` or `cache: 'force-cache'` stores the data across requests in a shared cache. You should avoid using it for user-specific data (i.e. requests that derive data from `cookies()` or `headers()`)
## Dynamic Data Fetching

Expand Down Expand Up @@ -207,7 +204,6 @@ export default async function Page({
{/* Send the artist information first,
and wrap albums in a suspense boundary */}
<Suspense fallback={<div>Loading...</div>}>
{/* @ts-expect-error Async Server Component */}
<Albums promise={albumData} />
</Suspense>
</>
Expand Down Expand Up @@ -301,7 +297,6 @@ export default async function Page({
<>
<h1>{artist.name}</h1>
<Suspense fallback={<div>Loading...</div>}>
{/* @ts-expect-error Async Server Component */}
<Playlists artistID={artist.id} />
</Suspense>
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ related:
- app/api-reference/functions/cookies
---

[Server Actions](#server-actions) are an **alpha** feature in Next.js, built on top of React [Actions](#actions). They enable server-side data mutations, reduced client-side JavaScript, and progressively enhanced forms.
[Server Actions](#server-actions) are an **alpha** feature in Next.js, built on top of React [Actions](#actions). They enable server-side data mutations, reduced client-side JavaScript, and progressively enhanced forms. They can be defined inside Server Components and/or called from Client Components:

```jsx filename="app/add-to-cart.js"
**With Server Components:**

```jsx filename="app/add-to-cart.jsx" highlight={5, 6, 13}
import { cookies } from 'next/headers'

// Server action defined inside a Server Component
export default function AddToCart({ productId }) {
async function addItem(data) {
'use server'
Expand All @@ -30,6 +33,32 @@ export default function AddToCart({ productId }) {
}
```
**With Client Components:**
```jsx filename="app/actions.js" highlight={1, 3}
'use server'

async function addItem(data) {
const cartId = cookies().get('cartId')?.value
await saveToDb({ cartId, data })
}
```
```jsx filename="app/add-to-cart.jsx" highlight={1, 3, 8}
'use client'

import { addItem } from './actions.js'

// Server Action being called inside a Client Component
export default function AddToCart({ productId }) {
return (
<form action={addItem}>
<button type="submit">Add to Cart</button>
</form>
)
}
```
## Convention
You can enable Server Actions in your Next.js project by enabling the **experimental** `serverActions` flag.
Expand All @@ -44,16 +73,27 @@ module.exports = {
### Creation
Server Actions can be defined in two places:
- Inside the component that uses it (Server Components only)
- In a separate file (Client and Server Components), for reusability. You can define multiple Server Actions in a single file.
#### With Server Components
Create a Server Action by defining an asynchronous function with the `"use server"` directive at the top of the function body. This function should have **serializable arguments** and a **serializable return value** based on the React Server Components protocol.
```jsx filename="app/components/component.js" highlight={2}
async function myAction() {
'use server'
// ...
```jsx filename="app/server-component.jsx" highlight={2}
export default function ServerComponent() {
async function myAction() {
'use server'
// ...
}
}
```
You can also use a top-level `"use server"` directive on top of a file. This can be useful if you have a single file that exports multiple Server Actions, and it is **required** if you're importing a Server Action in a Client Component.
#### With Client Components
If you're using a Server Action inside a Client Component, create your action in a separate file with the "use server" directive at the top of the file. Then, import the Server Action into your Client Component:
```jsx filename="app/actions.js" highlight={1}
'use server'
Expand All @@ -63,7 +103,21 @@ export async function myAction() {
}
```
> **Note:** When using a top-level `"use server"` directive, all exports will be considered Server Actions.
```jsx filename="app/client-component.jsx" highlight={1}
|"use client"

import { myAction } from './actions';

export default function ClientComponent() {
return (
<form action={myAction}>
<button type="submit">Add to Cart</button>
</form>
);
}
```
> **Note:** When using a top-level `"use server"` directive, all exports below will be considered Server Actions. You can have multiple Server Actions in a single file.
### Invocation
Expand Down Expand Up @@ -130,7 +184,7 @@ You can also invoke Server Actions without using `action` or `formAction`. You c
> **Note:** Using `startTransition` disables the out-of-the-box Progressive Enhancement.
```jsx filename="app/components/example-client-component.js" highlight={3, 7, 9}
```jsx filename="app/components/example-client-component.js" highlight={3, 7, 10}
'use client'

import { useTransition } from 'react'
Expand Down Expand Up @@ -336,7 +390,7 @@ export async function addItem() {
}
```
```jsx filename="app/components/example-client-component.js" highlight={3, 7, 9}
```jsx filename="app/components/example-client-component.js" highlight={3, 7, 10}
'use client'

import { useTransition } from 'react'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,24 +161,9 @@ For _complete_ end-to-end type safety, this also requires your database or conte

## Async Server Component TypeScript Error

- An `async` Server Components will cause a `'Promise<Element>' is not a valid JSX element` type error where it is used.
- This is a known issue with TypeScript and is being worked on upstream.
- As a temporary workaround, you can add `{/* @ts-expect-error Async Server Component */}` above the component to disable type checking for it.
To use an `async` Server Component with TypeScript, ensure you are using TypeScript `5.1.3` or higher and `@types/react` `18.2.8` or higher.

```tsx filename="app/page.tsx"
import { ExampleAsyncComponent } from './ExampleAsyncComponent'
export default function Page() {
return (
<>
{/* @ts-expect-error Async Server Component */}
<ExampleAsyncComponent />
</>
)
}
```

- This does not apply to Layout and Page components.
- We are tracking this [issue here](https://github.com/vercel/next.js/issues/42292). This will likely be fixed in TypeScript 5.1 (Stable).
If you are using an older version of TypeScript, you may see a `'Promise<Element>' is not a valid JSX element` type error. Updating to the latest version of TypeScript and `@types/react` should resolve this issue.

## Passing Data Between Server & Client Components

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ After you've updated, see the following sections for next steps:

Next.js 13 introduced the new [App Router](/docs/app/building-your-application/routing) with new features and conventions. The new Router is available in the `app` directory and co-exists with the `pages` directory.

Upgrading to Next.js 13 does **not** require using the new [App Router](/docs/app/building-your-application/routing#the-app-directory). You can continue using `pages` with new features that work in both directories, such as the updated [Image component](#image-component), [Link component](#link-component), [Script component](#script-component), and [Font optimization](#font-optimization).
Upgrading to Next.js 13 does **not** require using the new [App Router](/docs/app/building-your-application/routing#the-app-router). You can continue using `pages` with new features that work in both directories, such as the updated [Image component](#image-component), [Link component](#link-component), [Script component](#script-component), and [Font optimization](#font-optimization).

### `<Image/>` Component

Expand Down
36 changes: 34 additions & 2 deletions docs/02-app/02-api-reference/01-components/image.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ A `loader` is a function returning a URL string for the image, given the followi
Here is an example of using a custom loader:

```js
'use client'

import Image from 'next/image'

const imageLoader = ({ src, width, quality }) => {
Expand All @@ -148,6 +150,12 @@ export default function Page() {
}
```

<AppOnly>

> **Good to know:** Using props like `loader`, which accept a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function.
</AppOnly>

Alternatively, you can use the [loaderFile](#loaderfile) configuration in `next.config.js` to configure every instance of `next/image` in your application, without passing a prop.

### `fill`
Expand Down Expand Up @@ -271,13 +279,21 @@ Remember that the required width and height props can interact with your styling
### `onLoadingComplete`

```jsx
'use client'

<Image onLoadingComplete={(img) => console.log(img.naturalWidth)} />
```

A callback function that is invoked once the image is completely loaded and the [placeholder](#placeholder) has been removed.

The callback function will be called with one argument, a reference to the underlying `<img>` element.

<AppOnly>

> **Good to know:** Using props like `onLoadingComplete`, which accept a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function.
</AppOnly>

### `onLoad`

```jsx
Expand All @@ -286,9 +302,13 @@ The callback function will be called with one argument, a reference to the under

A callback function that is invoked when the image is loaded.

Note that the load event might occur before the placeholder is removed and the image is fully decoded.
The load event might occur before the image placeholder is removed and the image is fully decoded. If you want to wait until the image has fully loaded, use [`onLoadingComplete`](#onloadingcomplete) instead.

Instead, use [`onLoadingComplete`](#onloadingcomplete).
<AppOnly>

> **Good to know:** Using props like `onLoad`, which accept a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function.
</AppOnly>

### `onError`

Expand All @@ -298,6 +318,12 @@ Instead, use [`onLoadingComplete`](#onloadingcomplete).

A callback function that is invoked if the image fails to load.

<AppOnly>

> **Good to know:** Using props like `onError`, which accept a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function.
</AppOnly>

### `loading`

> **Recommendation**: This property is only meant for advanced use cases. Switching an image to load with `eager` will normally **hurt performance**. We recommend using the [`priority`](#priority) property instead, which will eagerly preload the image.
Expand Down Expand Up @@ -461,6 +487,12 @@ Examples:

- [Custom Image Loader Configuration](/docs/app/api-reference/next-config-js/images#example-loader-configuration)

<AppOnly>

> **Good to know:** Customizing the image loader file, which accepts a function, require using [Client Components](/docs/getting-started/react-essentials#client-components) to serialize the provided function.
</AppOnly>

## Advanced

The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates.
Expand Down
1 change: 1 addition & 0 deletions docs/02-app/02-api-reference/02-file-conventions/error.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,4 @@ export default function GlobalError({ error, reset }) {
> **Good to know:**
>
> - `global-error.js` replaces the root `layout.js` when active and so **must** define its own `<html>` and `<body>` tags.
> - While designing error UI, you may find it helpful to use the [React Developer Tools](https://react.dev/learn/react-developer-tools) to manually toggle Error boundaries.
4 changes: 4 additions & 0 deletions docs/02-app/02-api-reference/02-file-conventions/loading.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ export default function Loading() {
```

Loading UI components do not accept any parameters.

> **Good to know**
>
> - While designing loading UI, you may find it helpful to use the [React Developer Tools](https://react.dev/learn/react-developer-tools) to manually toggle Suspense boundaries.
6 changes: 2 additions & 4 deletions docs/02-app/02-api-reference/04-functions/cookies.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ related:

The `cookies` function allows you to read the HTTP incoming request cookies from a [Server Component](/docs/getting-started/react-essentials) or write outgoing request cookies in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/router-handlers).

> **Good to know:**
>
> - `cookies()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering)** at request time.
> **Good to know:** `cookies()` is a **[Dynamic Function](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-functions)** whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into **[dynamic rendering](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering)** at request time.
## `cookies().get(name)`

Expand Down Expand Up @@ -89,7 +87,7 @@ async function create(data) {

To "delete" a cookie, you must set a new cookie with the same name and an empty value. You can also set the `maxAge` to `0` to expire the cookie immediately.

> `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/router-handlers).
> **Good to know:** `.set()` is only available in a [Server Action](/docs/app/building-your-application/data-fetching/server-actions) or [Route Handler](/docs/app/building-your-application/routing/router-handlers).
```js filename="app/actions.js"
'use server';
Expand Down

0 comments on commit d8a9b5b

Please sign in to comment.