You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add`'use server'`at the top of an async function body to mark the function as callable by the client. We call these functions[_Server Functions_](/reference/rsc/server-functions).
26
+
Añade`'use server'`al principio del cuerpo de una función asíncrona para marcar la función como invocable desde el cliente. Llamamos a estas funciones[_Server Functions_](/reference/rsc/server-functions).
27
27
28
28
```js {2}
29
29
asyncfunctionaddToCart(data) {
@@ -32,78 +32,76 @@ async function addToCart(data) {
32
32
}
33
33
```
34
34
35
-
When calling a Server Function on the client, it will make a network request to the server that includes a serialized copy of any arguments passed. If the Server Function returns a value, that value will be serialized and returned to the client.
35
+
Cuando se llama a una Server Function desde el cliente, se realizará una petición de red al servidor que incluye una copia serializada de cualquier argumento pasado. Si la Server Function devuelve un valor, ese valor será serializado y devuelto al cliente.
36
36
37
-
Instead of individually marking functions with `'use server'`, you can add the directive to the top of a file to mark all exports within that file as Server Functions that can be used anywhere, including imported in client code.
37
+
En lugar de marcar funciones individualmente con `'use server'`, puedes añadir la directiva al principio de un archivo para marcar todas las funciones exportadas dentro de ese archivo como Server Functions, que pueden usarse en cualquier lugar, inclusive en código cliente.
38
38
39
-
#### Caveats {/*caveats*/}
40
-
*`'use server'`must be at the very beginning of their function or module; above any other code including imports (comments above directives are OK). They must be written with single or double quotes, not backticks.
41
-
*`'use server'`can only be used in server-side files. The resulting Server Functions can be passed to Client Components through props. See supported [types for serialization](#serializable-parameters-and-return-values).
42
-
*To import a Server Functions from [client code](/reference/rsc/use-client), the directive must be used on a module level.
43
-
*Because the underlying network calls are always asynchronous, `'use server'`can only be used on async functions.
44
-
*Always treat arguments to Server Functions as untrusted input and authorize any mutations. See [security considerations](#security).
45
-
* Server Functions should be called in a [Transition](/reference/react/useTransition). Server Functions passed to[`<form action>`](/reference/react-dom/components/form#props)or[`formAction`](/reference/react-dom/components/input#props)will automatically be called in a transition.
46
-
* Server Functions are designed for mutations that update server-side state; they are not recommended for data fetching. Accordingly, frameworks implementing Server Functions typically process one action at a time and do not have a way to cache the return value.
39
+
#### Advertencias {/*caveats*/}
40
+
*`'use server'`debe estar al principio de su función o módulo; por encima de cualquier otro código incluyendo importaciones (los comentarios por encima de las directivas están permitidos). Deben escribirse con comillas simples o dobles, no con comillas invertidas.
41
+
*`'use server'`solo puede usarse en archivos del lado del servidor. Las Server Functions resultantes pueden pasarse a Client Components a través de props. Consulta los [tipos compatibles para serialización](#serializable-parameters-and-return-values).
42
+
*Para importar Server Functions desde [código cliente](/reference/rsc/use-client), la directiva debe usarse a nivel de módulo.
43
+
*Debido a que las llamadas de red subyacentes son siempre asíncronas, `'use server'`solo puede usarse en funciones asíncronas.
44
+
*Siempre trata los argumentos de las Server Functions como entradas no confiables y autoriza cualquier mutación. Consulta [consideraciones de seguridad](#security).
45
+
*Las Server Functions deben llamarse en una [Transición](/reference/react/useTransition). Las Server Functions pasadas a[`<form action>`](/reference/react-dom/components/form#props)o[`formAction`](/reference/react-dom/components/input#props)se llamarán automáticamente en una transición.
46
+
*Las Server Functions están diseñadas para mutaciones que actualizan el estado del servidor; no se recomiendan para la obtención de datos. En consecuencia, los frameworks que implementan Server Functions típicamente procesan una acción a la vez y no tienen una forma de almacenar en caché el valor de retorno.
47
47
48
-
### Security considerations {/*security*/}
48
+
### Consideraciones de seguridad {/*security*/}
49
49
50
-
Arguments to Server Functions are fully client-controlled. For security, always treat them as untrusted input, and make sure to validate and escape arguments as appropriate.
50
+
Los argumentos de las Server Functions están completamente controlados por el cliente. Por seguridad, siempre trátalos como entradas no confiables y asegúrate de validar y escapar los argumentos según corresponda.
51
51
52
-
In any Server Function, make sure to validate that the logged-in user is allowed to perform that action.
52
+
En cualquier Server Function, asegúrate de validar que el usuario conectado está autorizado para realizar esa acción.
53
53
54
54
<Wip>
55
55
56
-
To prevent sending sensitive data from a Server Function, there are experimental taint APIs to prevent unique values and objects from being passed to client code.
56
+
Para evitar el envío de datos sensibles desde una Server Function, hay APIs experimentales de taint para evitar que valores y objetos únicos se pasen al código cliente.
* [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), only symbols registered in the global Symbol registry via [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for)
* [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) and [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
* Plain [objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object): those created with [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), with serializable properties
* Objects that are instances of any class (other than the built-ins mentioned) or objects with [a null prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)
93
-
* Symbols not registered globally, ex. `Symbol('my new symbol')`
94
-
* Events from event handlers
95
-
96
-
97
-
Supported serializable return values are the same as [serializable props](/reference/rsc/use-client#passing-props-from-server-to-client-components) for a boundary Client Component.
98
-
62
+
### Argumentos y valores de retorno serializables {/*serializable-parameters-and-return-values*/}
63
+
64
+
Dado que el código cliente llama a la Server Function a través de la red, cualquier argumento pasado necesitará ser serializable.
65
+
66
+
Aquí están los tipos compatibles para argumentos de Server Functions:
* [symbol](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Symbol), solo símbolos registrados en el registro global de Symbol mediante [`Symbol.for`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for)
* [TypedArray](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) y [ArrayBuffer](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
* Instancias de [FormData](https://developer.mozilla.org/es/docs/Web/API/FormData)
84
+
*[Objetos](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Object) planos: aquellos creados con [inicializadores de objeto](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Object_initializer), con propiedades serializables
* Objetos que son instancias de cualquier clase (aparte de las incorporadas mencionadas) u objetos con [un prototipo nulo](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)
93
+
* Símbolos no registrados globalmente, ej. `Symbol('my new symbol')`
94
+
* Eventos de controladores de eventos.
95
+
96
+
Los valores de retorno serializables compatibles son los mismos que las [props serializables](/reference/rsc/use-client#passing-props-from-server-to-client-components) para una barrera de Client Component.
99
97
100
98
## Uso {/*usage*/}
101
99
102
-
### Server Functions in forms {/*server-functions-in-forms*/}
100
+
### Server Functions en formularios {/*server-functions-in-forms*/}
103
101
104
-
The most common use case of Server Functions will be calling functions that mutate data. On the browser, the [HTML form element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)is the traditional approach for a user to submit a mutation. With React Server Components, React introduces first-class support for Server Functions as Actions in [forms](/reference/react-dom/components/form).
102
+
El caso de uso más común de las Server Functions será llamar a funciones que mutan datos. En el navegador, el [elemento HTML form](https://developer.mozilla.org/es/docs/Web/HTML/Element/form)es el enfoque tradicional para que un usuario envíe una mutación. Con React Server Components, React introduce soporte de primera clase para Server Functions como Acciones en [formularios](/reference/react-dom/components/form).
105
103
106
-
Here is a form that allows a user to request a username.
104
+
Aquí hay un formulario que permite solicitar un nombre de usuario.
107
105
108
106
```js [[1, 3, "formData"]]
109
107
// App.js
@@ -124,15 +122,15 @@ export default function App() {
124
122
}
125
123
```
126
124
127
-
In this example`requestUsername`is a Server Function passed to a `<form>`. When a user submits this form, there is a network request to the server function `requestUsername`. When calling a Server Function in a form, React will supply the form's <CodeStepstep={1}>[FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)</CodeStep> as the first argument to the Server Function.
125
+
En este ejemplo`requestUsername`es una Server Function pasada a un `<form>`. Cuando un usuario envía este formulario, hay una petición de red a la función del servidor `requestUsername`. Al llamar a una Server Function en un formulario, React proporcionará el [FormData](https://developer.mozilla.org/es/docs/Web/API/FormData) del formulario como el primer argumento de la Server Function.
128
126
129
-
By passing a Server Function to the form `action`, React can [progressively enhance](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement)the form. This means that forms can be submitted before the JavaScript bundle is loaded.
127
+
Al pasar una Server Function a la `action` del formulario, React puede [mejorar progresivamente](https://developer.mozilla.org/es/docs/Glossary/Progressive_Enhancement)el formulario. Esto significa que los formularios pueden enviarse antes de que se cargue el bundle de JavaScript.
130
128
131
-
#### Handling return values in forms {/*handling-return-values*/}
129
+
#### Manejo de valores de retorno en formularios {/*handling-return-values*/}
132
130
133
-
In the username request form, there might be the chance that a username is not available. `requestUsername`should tell us if it fails or not.
131
+
En la solicitud del formulario podría estar la posibilidad de que un nombre de usuario no esté disponible. `requestUsername`debería decirnos si falla o no.
134
132
135
-
To update the UI based on the result of a Server Function while supporting progressive enhancement, use[`useActionState`](/reference/react/useActionState).
133
+
Para actualizar la UI en base al resultado de una Server Function mientras se soporta mejora progresiva, usa[`useActionState`](/reference/react/useActionState).
136
134
137
135
```js
138
136
// requestUsername.js
@@ -170,13 +168,13 @@ function UsernameForm() {
170
168
}
171
169
```
172
170
173
-
Note that like most Hooks, `useActionState`can only be called in <CodeStepstep={1}>[client code](/reference/rsc/use-client)</CodeStep>.
171
+
Ten en cuenta que como la mayoría de los Hooks, `useActionState`solo puede llamarse en [código cliente](/reference/rsc/use-client).
174
172
175
-
### Calling a Server Function outside of`<form>` {/*calling-a-server-function-outside-of-form*/}
173
+
### Llamar a una Server Function fuera de`<form>` {/*calling-a-server-function-outside-of-form*/}
176
174
177
-
Server Functions are exposed server endpoints and can be called anywhere in client code.
175
+
Las Server Functions son endpoints del servidor expuestos y pueden llamarse desde cualquier lugar en el código cliente.
178
176
179
-
When using a Server Function outside a [form](/reference/react-dom/components/form), call the Server Function in a [Transition](/reference/react/useTransition), which allows you to display a loading indicator, show [optimistic state updates](/reference/react/useOptimistic), and handle unexpected errors. Forms will automatically wrap Server Functions in transitions.
177
+
Cuando uses una Server Function fuera de un [formulario](/reference/react-dom/components/form), llama a la Server Function en una [Transición](/reference/react/useTransition), lo que te permite mostrar un indicador de carga, mostrar [actualizaciones de estado optimistas](/reference/react/useOptimistic), y manejar errores inesperados. Los formularios envolverán automáticamente las Server Functions en transiciones.
180
178
181
179
```js {9-12}
182
180
importincrementLikefrom'./actions';
@@ -213,4 +211,4 @@ export default async function incrementLike() {
213
211
}
214
212
```
215
213
216
-
To read a Server Function return value, you'll need to `await`the promise returned.
214
+
Para leer un valor de retorno de una Server Function, necesitas usar `await`en la promesa que retorna.
0 commit comments