From fe90b04f9516562a11f0506f17c06c6d78af5265 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Thu, 28 Sep 2023 18:20:53 +0200 Subject: [PATCH] (docs) Document Server Actions `.bind` method (#56164) 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 `` 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. --- .../04-functions/server-actions.mdx | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/02-app/02-api-reference/04-functions/server-actions.mdx b/docs/02-app/02-api-reference/04-functions/server-actions.mdx index 27d5fc52d069..a28fd06c7640 100644 --- a/docs/02-app/02-api-reference/04-functions/server-actions.mdx +++ b/docs/02-app/02-api-reference/04-functions/server-actions.mdx @@ -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 ( +
+ + +
+ ) +} +``` + +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: