Skip to content

Commit 9bcff55

Browse files
authored
Translate user-server page (#996)
1 parent 0757df2 commit 9bcff55

File tree

1 file changed

+65
-67
lines changed

1 file changed

+65
-67
lines changed

src/content/reference/rsc/use-server.md

Lines changed: 65 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
title: "'use server'"
3-
titleForTitleTag: "'use server' directive"
3+
titleForTitleTag: "Directiva 'use server'"
44
---
55

66
<RSC>
@@ -23,7 +23,7 @@ titleForTitleTag: "'use server' directive"
2323

2424
### `'use server'` {/*use-server*/}
2525

26-
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).
2727

2828
```js {2}
2929
async function addToCart(data) {
@@ -32,78 +32,76 @@ async function addToCart(data) {
3232
}
3333
```
3434

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.
3636

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.
3838

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.
4747

48-
### Security considerations {/*security*/}
48+
### Consideraciones de seguridad {/*security*/}
4949

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.
5151

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.
5353

5454
<Wip>
5555

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.
5757

58-
See [experimental_taintUniqueValue](/reference/react/experimental_taintUniqueValue) and [experimental_taintObjectReference](/reference/react/experimental_taintObjectReference).
58+
Consulta [experimental_taintUniqueValue](/reference/react/experimental_taintUniqueValue) y [experimental_taintObjectReference](/reference/react/experimental_taintObjectReference).
5959

6060
</Wip>
6161

62-
### Serializable arguments and return values {/*serializable-parameters-and-return-values*/}
63-
64-
Since client code calls the Server Function over the network, any arguments passed will need to be serializable.
65-
66-
Here are supported types for Server Function arguments:
67-
68-
* Primitives
69-
* [string](https://developer.mozilla.org/en-US/docs/Glossary/String)
70-
* [number](https://developer.mozilla.org/en-US/docs/Glossary/Number)
71-
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
72-
* [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)
73-
* [undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)
74-
* [null](https://developer.mozilla.org/en-US/docs/Glossary/Null)
75-
* [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)
76-
* Iterables containing serializable values
77-
* [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
78-
* [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
79-
* [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
80-
* [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
81-
* [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)
82-
* [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
83-
* [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instances
84-
* 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
85-
* Functions that are Server Functions
86-
* [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
87-
88-
Notably, these are not supported:
89-
* React elements, or [JSX](/learn/writing-markup-with-jsx)
90-
* Functions, including component functions or any other function that is not a Server Function
91-
* [Classes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript)
92-
* 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:
67+
68+
* Primitivos
69+
* [string](https://developer.mozilla.org/es/docs/Glossary/String)
70+
* [number](https://developer.mozilla.org/es/docs/Glossary/Number)
71+
* [bigint](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
72+
* [boolean](https://developer.mozilla.org/es/docs/Glossary/Boolean)
73+
* [undefined](https://developer.mozilla.org/es/docs/Glossary/Undefined)
74+
* [null](https://developer.mozilla.org/es/docs/Glossary/Null)
75+
* [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)
76+
* Iterables que contienen valores serializables
77+
* [String](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/String)
78+
* [Array](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array)
79+
* [Map](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Map)
80+
* [Set](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Set)
81+
* [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)
82+
* [Date](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Date)
83+
* 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
85+
* Funciones que son Server Functions
86+
* [Promises](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise)
87+
88+
Notablemente, estos no son compatibles:
89+
* Elementos de React, o [JSX](/learn/writing-markup-with-jsx)
90+
* Funciones, incluyendo funciones de componente o cualquier otra función que no sea una Server Function
91+
* [Clases](https://developer.mozilla.org/es/docs/Learn/JavaScript/Objects/Classes_in_JavaScript)
92+
* 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.
9997

10098
## Uso {/*usage*/}
10199

102-
### Server Functions in forms {/*server-functions-in-forms*/}
100+
### Server Functions en formularios {/*server-functions-in-forms*/}
103101

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).
105103

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.
107105

108106
```js [[1, 3, "formData"]]
109107
// App.js
@@ -124,15 +122,15 @@ export default function App() {
124122
}
125123
```
126124

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 <CodeStep step={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.
128126

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.
130128

131-
#### Handling return values in forms {/*handling-return-values*/}
129+
#### Manejo de valores de retorno en formularios {/*handling-return-values*/}
132130

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.
134132

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).
136134

137135
```js
138136
// requestUsername.js
@@ -170,13 +168,13 @@ function UsernameForm() {
170168
}
171169
```
172170

173-
Note that like most Hooks, `useActionState` can only be called in <CodeStep step={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).
174172

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*/}
176174

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.
178176

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.
180178

181179
```js {9-12}
182180
import incrementLike from './actions';
@@ -213,4 +211,4 @@ export default async function incrementLike() {
213211
}
214212
```
215213

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

Comments
 (0)