Skip to content

Commit dfbbf48

Browse files
committed
Translate useActionState.md to pt-br
1 parent 7148d38 commit dfbbf48

File tree

1 file changed

+51
-51
lines changed

1 file changed

+51
-51
lines changed

src/content/reference/react/useActionState.md

+51-51
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,19 @@ canary: true
55

66
<Canary>
77

8-
The `useActionState` Hook is currently only available in React's Canary and experimental channels. Learn more about [release channels here](/community/versioning-policy#all-release-channels). In addition, you need to use a framework that supports [React Server Components](/reference/rsc/use-client) to get the full benefit of `useActionState`.
8+
O Hook `useActionState` está atualmente disponível apenas nos canais Canary e experimentais do React. Saiba mais sobre [canais de lançamento aqui](/community/versioning-policy#all-release-channels). Além disso, você precisa usar um framework que suporte [React Server Components](/reference/rsc/use-client) para obter o máximo benefício do `useActionState`.
99

1010
</Canary>
1111

1212
<Note>
1313

14-
In earlier React Canary versions, this API was part of React DOM and called `useFormState`.
14+
Nas versões anteriores do React Canary, esta API fazia parte do React DOM e era chamada de `useFormState`.
1515

1616
</Note>
1717

1818
<Intro>
1919

20-
`useActionState` is a Hook that allows you to update state based on the result of a form action.
20+
`useActionState` é um Hook que permite atualizar o estado com base no resultado de uma ação de formulário.
2121

2222
```js
2323
const [state, formAction] = useActionState(fn, initialState, permalink?);
@@ -29,13 +29,13 @@ const [state, formAction] = useActionState(fn, initialState, permalink?);
2929
3030
---
3131
32-
## Reference {/*reference*/}
32+
## Referência {/*reference*/}
3333
3434
### `useActionState(action, initialState, permalink?)` {/*useactionstate*/}
3535
36-
{/* TODO T164397693: link to actions documentation once it exists */}
36+
{/* TODO T164397693: link para a documentação de ações assim que ela existir */}
3737
38-
Call `useActionState` at the top level of your component to create component state that is updated [when a form action is invoked](/reference/react-dom/components/form). You pass `useActionState` an existing form action function as well as an initial state, and it returns a new action that you use in your form, along with the latest form state. The latest form state is also passed to the function that you provided.
38+
Chame `useActionState` no nível superior do seu componente para criar um estado de componente que é atualizado [quando uma ação de formulário é invocada](/reference/react-dom/components/form). Você passa para `useActionState` uma função de ação de formulário existente, bem como um estado inicial, e ele retorna uma nova ação que você usa em seu formulário, juntamente com o estado mais recente do formulário. O estado mais recente do formulário também é passado para a função que você forneceu.
3939
4040
```js
4141
import { useActionState } from "react";
@@ -49,45 +49,45 @@ function StatefulForm({}) {
4949
return (
5050
<form>
5151
{state}
52-
<button formAction={formAction}>Increment</button>
52+
<button formAction={formAction}>Incrementar</button>
5353
</form>
5454
)
5555
}
5656
```
5757
58-
The form state is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial state that you pass.
58+
O estado do formulário é o valor retornado pela ação quando o formulário foi submetido pela última vez. Se o formulário ainda não foi submetido, é o estado inicial que você passa.
5959
60-
If used with a Server Action, `useActionState` allows the server's response from submitting the form to be shown even before hydration has completed.
60+
Se usado com uma Ação do Servidor, `useActionState` permite que a resposta do servidor da submissão do formulário seja exibida mesmo antes que a hidratação tenha sido concluída.
6161
62-
[See more examples below.](#usage)
62+
[Veja mais exemplos abaixo.](#usage)
6363
64-
#### Parameters {/*parameters*/}
64+
#### Parâmetros {/*parameters*/}
6565
66-
* `fn`: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous state of the form (initially the `initialState` that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.
67-
* `initialState`: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.
68-
* **optional** `permalink`: A string containing the unique page URL that this form modifies. For use on pages with dynamic content (eg: feeds) in conjunction with progressive enhancement: if `fn` is a [server action](/reference/rsc/use-server) and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL, rather than the current page's URL. Ensure that the same form component is rendered on the destination page (including the same action `fn` and `permalink`) so that React knows how to pass the state through. Once the form has been hydrated, this parameter has no effect.
66+
* `fn`: A função a ser chamada quando o formulário é submetido ou o botão pressionado. Quando a função é chamada, ela receberá o estado anterior do formulário (inicialmente o `initialState` que você passa, posteriormente seu último valor de retorno) como seu argumento inicial, seguido pelos argumentos que uma ação de formulário normalmente recebe.
67+
* `initialState`: O valor que você deseja que o estado tenha inicialmente. Ele pode ser qualquer valor serializável. Este argumento é ignorado após a ação ser invocada pela primeira vez.
68+
* **opcional** `permalink`: Uma string contendo a URL única da página que este formulário modifica. Para uso em páginas com conteúdo dinâmico (por exemplo: feeds) em conjunto com aprimoramento progressivo: se `fn` for uma [ação do servidor](/reference/rsc/use-server) e o formulário for submetido antes que o pacote JavaScript carregue, o navegador navegará para a URL permalink especificada, em vez da URL da página atual. Certifique-se de que o mesmo componente de formulário seja renderizado na página de destino (incluindo a mesma ação `fn` e `permalink`) para que o React saiba como passar o estado. Uma vez que o formulário tenha sido hidratado, este parâmetro não tem efeito.
6969
70-
{/* TODO T164397693: link to serializable values docs once it exists */}
70+
{/* TODO T164397693: link para a documentação de valores serializáveis assim que existir */}
7171
72-
#### Returns {/*returns*/}
72+
#### Retorna {/*returns*/}
7373
74-
`useActionState` returns an array with exactly two values:
74+
`useActionState` retorna um array com exatamente dois valores:
7575
76-
1. The current state. During the first render, it will match the `initialState` you have passed. After the action is invoked, it will match the value returned by the action.
77-
2. A new action that you can pass as the `action` prop to your `form` component or `formAction` prop to any `button` component within the form.
76+
1. O estado atual. Durante a primeira renderização, ele corresponderá ao `initialState` que você passou. Após a invocação da ação, ele corresponderá ao valor retornado pela ação.
77+
2. Uma nova ação que você pode passar como a prop `action` para seu componente `form` ou prop `formAction` para qualquer componente `button` dentro do formulário.
7878
79-
#### Caveats {/*caveats*/}
79+
#### Ressalvas {/*caveats*/}
8080
81-
* When used with a framework that supports React Server Components, `useActionState` lets you make forms interactive before JavaScript has executed on the client. When used without Server Components, it is equivalent to component local state.
82-
* The function passed to `useActionState` receives an extra argument, the previous or initial state, as its first argument. This makes its signature different than if it were used directly as a form action without using `useActionState`.
81+
* Quando usado com um framework que suporta React Server Components, `useActionState` permite que você torne os formulários interativos antes que o JavaScript tenha sido executado no cliente. Quando usado sem Server Components, é equivalente ao estado local do componente.
82+
* A função passada para `useActionState` recebe um argumento extra, o estado anterior ou inicial, como seu primeiro argumento. Isso torna sua assinatura diferente do que se ela fosse usada diretamente como uma ação de formulário sem usar `useActionState`.
8383
8484
---
8585
86-
## Usage {/*usage*/}
86+
## Uso {/*usage*/}
8787
88-
### Using information returned by a form action {/*using-information-returned-by-a-form-action*/}
88+
### Usando informações retornadas por uma ação de formulário {/*using-information-returned-by-a-form-action*/}
8989
90-
Call `useActionState` at the top level of your component to access the return value of an action from the last time a form was submitted.
90+
Chame `useActionState` no nível superior do seu componente para acessar o valor retornado de uma ação da última vez que um formulário foi submetido.
9191
9292
```js [[1, 5, "state"], [2, 5, "formAction"], [3, 5, "action"], [4, 5, "null"], [2, 8, "formAction"]]
9393
import { useActionState } from 'react';
@@ -104,27 +104,27 @@ function MyComponent() {
104104
}
105105
```
106106
107-
`useActionState` returns an array with exactly two items:
107+
`useActionState` retorna um array com exatamente dois itens:
108108
109-
1. The <CodeStep step={1}>current state</CodeStep> of the form, which is initially set to the <CodeStep step={4}>initial state</CodeStep> you provided, and after the form is submitted is set to the return value of the <CodeStep step={3}>action</CodeStep> you provided.
110-
2. A <CodeStep step={2}>new action</CodeStep> that you pass to `<form>` as its `action` prop.
109+
1. O <CodeStep step={1}>estado atual</CodeStep> do formulário, que é inicialmente definido para o <CodeStep step={4}>estado inicial</CodeStep> que você forneceu, e após a submissão do formulário é definido para o valor de retorno da <CodeStep step={3}>ação</CodeStep> que você forneceu.
110+
2. Uma <CodeStep step={2}>nova ação</CodeStep> que você passa para `<form>` como sua prop `action`.
111111
112-
When the form is submitted, the <CodeStep step={3}>action</CodeStep> function that you provided will be called. Its return value will become the new <CodeStep step={1}>current state</CodeStep> of the form.
112+
Quando o formulário é submetido, a função <CodeStep step={3}>ação</CodeStep> que você forneceu será chamada. Seu valor de retorno se tornará o novo <CodeStep step={1}>estado atual</CodeStep> do formulário.
113113
114-
The <CodeStep step={3}>action</CodeStep> that you provide will also receive a new first argument, namely the <CodeStep step={1}>current state</CodeStep> of the form. The first time the form is submitted, this will be the <CodeStep step={4}>initial state</CodeStep> you provided, while with subsequent submissions, it will be the return value from the last time the action was called. The rest of the arguments are the same as if `useActionState` had not been used.
114+
A <CodeStep step={3}>ação</CodeStep> que você fornece também receberá um novo primeiro argumento, que é o <CodeStep step={1}>estado atual</CodeStep> do formulário. A primeira vez que o formulário é submetido, isso será o <CodeStep step={4}>estado inicial</CodeStep> que você forneceu, enquanto em submissões subsequentes, será o valor de retorno da última vez em que a ação foi chamada. O restante dos argumentos é o mesmo do que se `useActionState` não tivesse sido usado.
115115
116116
```js [[3, 1, "action"], [1, 1, "currentState"]]
117117
function action(currentState, formData) {
118118
// ...
119-
return 'next state';
119+
return 'próximo estado';
120120
}
121121
```
122122
123-
<Recipes titleText="Display information after submitting a form" titleId="display-information-after-submitting-a-form">
123+
<Recipes titleText="Exibir informações após submeter um formulário" titleId="display-information-after-submitting-a-form">
124124
125-
#### Display form errors {/*display-form-errors*/}
125+
#### Exibir erros de formulário {/*display-form-errors*/}
126126
127-
To display messages such as an error message or toast that's returned by a Server Action, wrap the action in a call to `useActionState`.
127+
Para exibir mensagens como uma mensagem de erro ou um toast que é retornado por uma Ação do Servidor, envolva a ação em uma chamada para `useActionState`.
128128
129129
<Sandpack>
130130
@@ -138,7 +138,7 @@ function AddToCartForm({itemID, itemTitle}) {
138138
<form action={formAction}>
139139
<h2>{itemTitle}</h2>
140140
<input type="hidden" name="itemID" value={itemID} />
141-
<button type="submit">Add to Cart</button>
141+
<button type="submit">Adicionar ao Carrinho</button>
142142
{message}
143143
</form>
144144
);
@@ -147,8 +147,8 @@ function AddToCartForm({itemID, itemTitle}) {
147147
export default function App() {
148148
return (
149149
<>
150-
<AddToCartForm itemID="1" itemTitle="JavaScript: The Definitive Guide" />
151-
<AddToCartForm itemID="2" itemTitle="JavaScript: The Good Parts" />
150+
<AddToCartForm itemID="1" itemTitle="JavaScript: O Guia Definitivo" />
151+
<AddToCartForm itemID="2" itemTitle="JavaScript: Os Bons Partes" />
152152
</>
153153
)
154154
}
@@ -160,9 +160,9 @@ export default function App() {
160160
export async function addToCart(prevState, queryData) {
161161
const itemID = queryData.get('itemID');
162162
if (itemID === "1") {
163-
return "Added to cart";
163+
return "Adicionado ao carrinho";
164164
} else {
165-
return "Couldn't add to cart: the item is sold out.";
165+
return "Não foi possível adicionar ao carrinho: o item está esgotado.";
166166
}
167167
}
168168
```
@@ -194,9 +194,9 @@ form button {
194194
195195
<Solution />
196196
197-
#### Display structured information after submitting a form {/*display-structured-information-after-submitting-a-form*/}
197+
#### Exibir informações estruturadas após submeter um formulário {/*display-structured-information-after-submitting-a-form*/}
198198
199-
The return value from a Server Action can be any serializable value. For example, it could be an object that includes a boolean indicating whether the action was successful, an error message, or updated information.
199+
O valor de retorno de uma Ação do Servidor pode ser qualquer valor serializável. Por exemplo, pode ser um objeto que inclui um booleano indicando se a ação foi bem-sucedida, uma mensagem de erro ou informações atualizadas.
200200
201201
<Sandpack>
202202
@@ -210,15 +210,15 @@ function AddToCartForm({itemID, itemTitle}) {
210210
<form action={formAction}>
211211
<h2>{itemTitle}</h2>
212212
<input type="hidden" name="itemID" value={itemID} />
213-
<button type="submit">Add to Cart</button>
213+
<button type="submit">Adicionar ao Carrinho</button>
214214
{formState?.success &&
215215
<div className="toast">
216-
Added to cart! Your cart now has {formState.cartSize} items.
216+
Adicionado ao carrinho! Seu carrinho agora tem {formState.cartSize} itens.
217217
</div>
218218
}
219219
{formState?.success === false &&
220220
<div className="error">
221-
Failed to add to cart: {formState.message}
221+
Falha ao adicionar ao carrinho: {formState.message}
222222
</div>
223223
}
224224
</form>
@@ -228,8 +228,8 @@ function AddToCartForm({itemID, itemTitle}) {
228228
export default function App() {
229229
return (
230230
<>
231-
<AddToCartForm itemID="1" itemTitle="JavaScript: The Definitive Guide" />
232-
<AddToCartForm itemID="2" itemTitle="JavaScript: The Good Parts" />
231+
<AddToCartForm itemID="1" itemTitle="JavaScript: O Guia Definitivo" />
232+
<AddToCartForm itemID="2" itemTitle="JavaScript: Os Bons Partes" />
233233
</>
234234
)
235235
}
@@ -248,7 +248,7 @@ export async function addToCart(prevState, queryData) {
248248
} else {
249249
return {
250250
success: false,
251-
message: "The item is sold out.",
251+
message: "O item está esgotado.",
252252
};
253253
}
254254
}
@@ -283,14 +283,14 @@ form button {
283283
284284
</Recipes>
285285
286-
## Troubleshooting {/*troubleshooting*/}
286+
## Solução de Problemas {/*troubleshooting*/}
287287
288-
### My action can no longer read the submitted form data {/*my-action-can-no-longer-read-the-submitted-form-data*/}
288+
### Minha ação não consegue mais ler os dados do formulário submetido {/*my-action-can-no-longer-read-the-submitted-form-data*/}
289289
290-
When you wrap an action with `useActionState`, it gets an extra argument *as its first argument*. The submitted form data is therefore its *second* argument instead of its first as it would usually be. The new first argument that gets added is the current state of the form.
290+
Quando você envolve uma ação com `useActionState`, ela recebe um argumento extra *como seu primeiro argumento*. Os dados do formulário submetido são, portanto, seu *segundo* argumento em vez de seu primeiro, como geralmente seria. O novo primeiro argumento que é adicionado é o estado atual do formulário.
291291
292292
```js
293293
function action(currentState, formData) {
294294
// ...
295295
}
296-
```
296+
```

0 commit comments

Comments
 (0)