Skip to content

Commit d32fc29

Browse files
Translate use-server.md to Portuguese (#1073)
* Translate `use-server.md` to Portuguese * Update use-server.md remove indent spaces
1 parent 39a9149 commit d32fc29

File tree

1 file changed

+69
-70
lines changed

1 file changed

+69
-70
lines changed
Lines changed: 69 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,29 @@
11
---
22
title: "'use server'"
3-
titleForTitleTag: "'use server' directive"
3+
titleForTitleTag: "Diretiva `'use server'`"
44
---
55

66
<RSC>
77

8-
`'use server'` is for use with [using React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks).
8+
`'use server'` deve ser usado com [usando React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks).
99

1010
</RSC>
1111

12-
1312
<Intro>
1413

15-
`'use server'` marks server-side functions that can be called from client-side code.
14+
`'use server'` marca funções do lado do servidor que podem ser chamadas a partir do código do lado do cliente.
1615

1716
</Intro>
1817

1918
<InlineToc />
2019

2120
---
2221

23-
## Reference {/*reference*/}
22+
## Referência {/*reference*/}
2423

2524
### `'use server'` {/*use-server*/}
2625

27-
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+
Adicione `'use server'` no início do corpo de uma função `async` para marcar a função como chamável pelo cliente. Chamamos essas funções de [_Funções do Servidor_](/reference/rsc/server-functions).
2827

2928
```js {2}
3029
async function addToCart(data) {
@@ -33,78 +32,78 @@ async function addToCart(data) {
3332
}
3433
```
3534

36-
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+
Ao chamar uma Server Function no cliente, ela fará uma requisição de rede ao servidor que inclui uma cópia serializada de quaisquer argumentos passados. Se a Server Function retornar um valor, esse valor será serializado e retornado ao cliente.
36+
37+
Em vez de marcar funções individualmente com `'use server'`, você pode adicionar a diretiva no topo de um arquivo para marcar todas as exportações dentro desse arquivo como Server Functions que podem ser usadas em qualquer lugar, inclusive importadas no código do cliente.
3738

38-
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.
39+
#### Ressalvas {/*caveats*/}
3940

40-
#### Caveats {/*caveats*/}
41-
* `'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.
42-
* `'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).
43-
* To import a Server Functions from [client code](/reference/rsc/use-client), the directive must be used on a module level.
44-
* Because the underlying network calls are always asynchronous, `'use server'` can only be used on async functions.
45-
* Always treat arguments to Server Functions as untrusted input and authorize any mutations. See [security considerations](#security).
46-
* 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.
47-
* 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.
41+
* `'use server'` deve estar no início da função ou módulo; acima de qualquer outro código, incluindo imports (comentários acima das diretivas são OK). Elas devem ser escritas com aspas simples ou duplas, não crases.
42+
* `'use server'` só pode ser usado em arquivos do lado do servidor. As Server Functions resultantes podem ser passadas para Client Components por meio de props. Veja os [tipos suportados para serialização](#serializable-parameters-and-return-values).
43+
* Para importar Server Functions do [código do cliente](/reference/rsc/use-client), a diretiva deve ser usada em nível de módulo.
44+
* Como as chamadas de rede subjacentes são sempre assíncronas, `'use server'` só pode ser usado em funções `async`.
45+
* Sempre trate os argumentos das Server Functions como entrada não confiável e autorize quaisquer mutações. Veja [considerações de segurança](#security).
46+
* As Server Functions devem ser chamadas em uma [Transition](/reference/react/useTransition). Server Functions passadas para [`<form action>`](/reference/react-dom/components/form#props) ou [`formAction`](/reference/react-dom/components/input#props) serão automaticamente chamadas em uma transition.
47+
* As Server Functions são projetadas para mutações que atualizam o estado do lado do servidor; não são recomendadas para busca de dados. Consequentemente, frameworks que implementam Server Functions normalmente processam uma ação por vez e não têm uma maneira de armazenar em cache o valor de retorno.
4848

49-
### Security considerations {/*security*/}
49+
### Considerações de segurança {/*security*/}
5050

51-
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.
51+
Os argumentos das Server Functions são totalmente controlados pelo cliente. Para segurança, sempre trate-os como entrada não confiável e certifique-se de validar e escapar dos argumentos conforme apropriado.
5252

53-
In any Server Function, make sure to validate that the logged-in user is allowed to perform that action.
53+
Em qualquer Server Function, certifique-se de validar se o usuário logado tem permissão para executar essa ação.
5454

5555
<Wip>
5656

57-
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.
57+
Para evitar o envio de dados sensíveis de uma Server Function, existem APIs experimentais de taint para impedir que valores e objetos exclusivos sejam passados para o código do cliente.
5858

59-
See [experimental_taintUniqueValue](/reference/react/experimental_taintUniqueValue) and [experimental_taintObjectReference](/reference/react/experimental_taintObjectReference).
59+
Veja [experimental_taintUniqueValue](/reference/react/experimental_taintUniqueValue) e [experimental_taintObjectReference](/reference/react/experimental_taintObjectReference).
6060

6161
</Wip>
6262

63-
### Serializable arguments and return values {/*serializable-parameters-and-return-values*/}
64-
65-
Since client code calls the Server Function over the network, any arguments passed will need to be serializable.
66-
67-
Here are supported types for Server Function arguments:
68-
69-
* Primitives
70-
* [string](https://developer.mozilla.org/en-US/docs/Glossary/String)
71-
* [number](https://developer.mozilla.org/en-US/docs/Glossary/Number)
72-
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
73-
* [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)
74-
* [undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)
75-
* [null](https://developer.mozilla.org/en-US/docs/Glossary/Null)
76-
* [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)
77-
* Iterables containing serializable values
78-
* [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
79-
* [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
80-
* [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
81-
* [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
82-
* [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)
63+
### Argumentos e valores de retorno serializáveis {/*serializable-parameters-and-return-values*/}
64+
65+
Como o código do cliente chama a Server Function pela rede, quaisquer argumentos passados precisarão ser serializáveis.
66+
67+
Aqui estão os tipos suportados para os argumentos da Server Function:
68+
69+
* Primitivos
70+
* [string](https://developer.mozilla.org/en-US/docs/Glossary/String)
71+
* [number](https://developer.mozilla.org/en-US/docs/Glossary/Number)
72+
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
73+
* [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean)
74+
* [undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined)
75+
* [null](https://developer.mozilla.org/en-US/docs/Glossary/Null)
76+
* [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), apenas símbolos registrados no registro global de Symbol via [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for)
77+
* Iteráveis contendo valores serializáveis
78+
* [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
79+
* [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
80+
* [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
81+
* [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
82+
* [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) e [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
8383
* [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
84-
* [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instances
85-
* 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
86-
* Functions that are Server Functions
84+
* Instâncias [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
85+
* [Objetos](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) simples: aqueles criados com [inicializadores de objeto](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), com propriedades serializáveis
86+
* Funções que são Server Functions
8787
* [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
8888

89-
Notably, these are not supported:
90-
* React elements, or [JSX](/learn/writing-markup-with-jsx)
91-
* Functions, including component functions or any other function that is not a Server Function
92-
* [Classes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript)
93-
* 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)
94-
* Symbols not registered globally, ex. `Symbol('my new symbol')`
95-
* Events from event handlers
89+
Notavelmente, estes não são suportados:
9690

91+
* Elementos React ou [JSX](/learn/writing-markup-with-jsx)
92+
* Funções, incluindo funções de componente ou qualquer outra função que não seja uma Server Function
93+
* [Classes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript)
94+
* Objetos que são instâncias de qualquer classe (além dos built-ins mencionados) ou objetos com [um protótipo nulo](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects)
95+
* Símbolos não registrados globalmente, ex. `Symbol('meu novo símbolo')`
96+
* Eventos de manipuladores de eventos
9797

98-
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.
99-
98+
Os valores de retorno serializáveis suportados são os mesmos que os [props serializáveis](/reference/rsc/use-client#passing-props-from-server-to-client-components) para um Client Component de limite.
10099

101-
## Usage {/*usage*/}
100+
## Uso {/*usage*/}
102101

103-
### Server Functions in forms {/*server-functions-in-forms*/}
102+
### Server Functions em formulários {/*server-functions-in-forms*/}
104103

105-
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).
104+
O caso de uso mais comum das Server Functions será chamar funções que mutam dados. No navegador, o [elemento de formulário HTML](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) é a abordagem tradicional para um usuário enviar uma mutação. Com React Server Components, o React introduz suporte de primeira classe para Server Functions como Actions em [formulários](/reference/react-dom/components/form).
106105

107-
Here is a form that allows a user to request a username.
106+
Aqui está um formulário que permite a um usuário solicitar um nome de usuário.
108107

109108
```js [[1, 3, "formData"]]
110109
// App.js
@@ -125,15 +124,15 @@ export default function App() {
125124
}
126125
```
127126

128-
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.
127+
Neste exemplo, `requestUsername` é uma Server Function passada para um `<form>`. Quando um usuário envia este formulário, há uma requisição de rede para a função do servidor `requestUsername`. Ao chamar uma Server Function em um formulário, o React fornecerá o <CodeStep step={1}>[FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)</CodeStep> do formulário como o primeiro argumento para a Server Function.
129128

130-
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.
129+
Ao passar uma Server Function para o formulário `action`, o React pode [aprimorar progressivamente](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement) o formulário. Isso significa que formulários podem ser enviados antes que o bundle JavaScript seja carregado.
131130

132-
#### Handling return values in forms {/*handling-return-values*/}
131+
#### Manipulando valores de retorno em formulários {/*handling-return-values*/}
133132

134-
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.
133+
No formulário de solicitação de nome de usuário, pode haver a chance de um nome de usuário não estar disponível. `requestUsername` deve nos dizer se falha ou não.
135134

136-
To update the UI based on the result of a Server Function while supporting progressive enhancement, use [`useActionState`](/reference/react/useActionState).
135+
Para atualizar a UI com base no resultado de uma Server Function ao mesmo tempo em que suporta o aprimoramento progressivo, use [`useActionState`](/reference/react/useActionState).
137136

138137
```js
139138
// requestUsername.js
@@ -165,19 +164,19 @@ function UsernameForm() {
165164
<input type="text" name="username" />
166165
<button type="submit">Request</button>
167166
</form>
168-
<p>Last submission request returned: {state}</p>
167+
<p>Última solicitação de envio retornou: {state}</p>
169168
</>
170169
);
171170
}
172171
```
173172

174-
Note that like most Hooks, `useActionState` can only be called in <CodeStep step={1}>[client code](/reference/rsc/use-client)</CodeStep>.
173+
Observe que, como a maioria dos Hooks, `useActionState` só pode ser chamado em <CodeStep step={1}>[código do cliente](/reference/rsc/use-client)</CodeStep>.
175174

176-
### Calling a Server Function outside of `<form>` {/*calling-a-server-function-outside-of-form*/}
175+
### Chamando uma Server Function fora de `<form>` {/*calling-a-server-function-outside-of-form*/}
177176

178-
Server Functions are exposed server endpoints and can be called anywhere in client code.
177+
As Server Functions são expostas como endpoints do servidor e podem ser chamadas em qualquer lugar no código do cliente.
179178

180-
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.
179+
Ao usar uma Server Function fora de um [formulário](/reference/react-dom/components/form), chame a Server Function em uma [Transition](/reference/react/useTransition), que permite que você exiba um indicador de carregamento, mostre [atualizações de estado otimistas](/reference/react/useOptimistic) e lide com erros inesperados. Os formulários automaticamente encapsularão Server Functions em transitions.
181180

182181
```js {9-12}
183182
import incrementLike from './actions';
@@ -196,8 +195,8 @@ function LikeButton() {
196195

197196
return (
198197
<>
199-
<p>Total Likes: {likeCount}</p>
200-
<button onClick={onClick} disabled={isPending}>Like</button>;
198+
<p>Total de curtidas: {likeCount}</p>
199+
<button onClick={onClick} disabled={isPending}>Curtir</button>;
201200
</>
202201
);
203202
}
@@ -214,4 +213,4 @@ export default async function incrementLike() {
214213
}
215214
```
216215

217-
To read a Server Function return value, you'll need to `await` the promise returned.
216+
Para ler um valor de retorno da Server Function, você precisará fazer `await` na promise retornada.

0 commit comments

Comments
 (0)