Skip to content

Commit

Permalink
(docs) Document Server Actions .bind method (#56164)
Browse files Browse the repository at this point in the history
This will be the recommended way of passing extra arguments to a Server Action. A couple of reasons behind:

- This is better than putting a hidden `<input hidden value={userId}/>` because that will appear in the SSR'd HTML as full text and cannot be encoded. With `.bind`, we can handle that in the future.
- This is better than event callbacks `onSubmit={(e) => { await updateUser(userId, e.target.formData) }}` as this supports progressive enhancement.
- This is better than re-creating a new action `action={async (formData) => { "use server"; return updateUser(userId, formData) }}` as inlined `"use server"` only works in Server Components.
  • Loading branch information
shuding committed Sep 28, 2023
1 parent 9cd46e3 commit fe90b04
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions docs/02-app/02-api-reference/04-functions/server-actions.mdx
Expand Up @@ -96,6 +96,39 @@ export default function ClientComponent({ myAction }) {
}
```

### Binding Arguments

You can bind arguments to a Server Action using the `bind` method. This allows you to create a new Server Action with some arguments already bound. This is beneficial when you want to pass extra arguments to a Server Action.

```jsx filename="app/client-component.jsx" highlight={6}
'use client'

import { updateUser } from './actions'

export function UserProfile({ userId }) {
const updateUserWithId = updateUser.bind(null, userId)

return (
<form action={updateUserWithId}>
<input type="text" name="name" />
<button type="submit">Update User Name</button>
</form>
)
}
```

And then, the `updateUser` Server Action will always receive the `userId` argument, in addition to the form data:

```js filename="app/actions.js"
'use server'

export async function updateUser(userId, formData) {
// ...
}
```

> **Good to know**: `.bind` of a Server Action works in both Server and Client Components. It also supports [Progressive Enhancement](#progressive-enhancement).
## Invocation

You can invoke Server Actions using the following methods:
Expand Down

0 comments on commit fe90b04

Please sign in to comment.