Skip to content

Translate useActionState.md to Portuguese #1062

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
3510e96
Translate `useActionState.md` to Portuguese
NivaldoFarias Mar 20, 2025
eeef5a1
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
e60b3f9
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
973daf2
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
1ad01fe
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
163541a
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
56fdb33
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
f914fe5
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
8ca1543
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
3b3595c
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
d8803e5
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
2d0860a
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
dbfcad0
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
06f06e0
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
b9f6262
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
00f529c
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
428a919
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
5183f82
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
6b4a840
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
602fb2f
Update src/content/reference/react/useActionState.md
jhonmike Apr 22, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 37 additions & 38 deletions src/content/reference/react/useActionState.md
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ title: useActionState

<Intro>

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

```js
const [state, formAction, isPending] = useActionState(fn, initialState, permalink?);
@@ -14,22 +14,21 @@ const [state, formAction, isPending] = useActionState(fn, initialState, permalin

<Note>

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

</Note>


<InlineToc />

---

## Reference {/*reference*/}
## Referência {/*reference*/}

### `useActionState(action, initialState, permalink?)` {/*useactionstate*/}

{/* TODO T164397693: link to actions documentation once it exists */}

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 and whether the Action is still pending. The latest form state is also passed to the function that you provided.
Chame `useActionState` no nível superior do seu componente para criar um estado do componente que é atualizado [quando uma ação de formulário é invocada](/reference/react-dom/components/form). Você passa para o `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 no seu formulário, juntamente com o estado atual do formulário e se a ação ainda está pendente. O estado atual do formulário também é passado para a função que você forneceu.

```js
import { useActionState } from "react";
@@ -49,40 +48,40 @@ function StatefulForm({}) {
}
```

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.
O estado do formulário é o valor retornado pela ação quando o formulário foi enviado pela última vez. Se o formulário ainda não foi enviado, é o estado inicial que você passa.

If used with a Server Function, `useActionState` allows the server's response from submitting the form to be shown even before hydration has completed.
Quando usado com uma Função de Servidor, `useActionState` permite que a resposta do servidor ao enviar o formulário seja exibida mesmo antes da hidratação ser concluída.

[See more examples below.](#usage)
[Veja mais exemplos abaixo.](#usage)

#### Parameters {/*parameters*/}
#### Parâmetros {/*parameters*/}

* `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.
* `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.
* **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 function](/reference/rsc/server-functions) 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.
* `fn`: A função a ser chamada quando o formulário é enviado ou o botão pressionado. Quando a função é chamada, ela receberá o estado anterior do formulário (inicialmente o `initialState` que você passa, subsequentemente seu valor de retorno anterior) como seu primeiro argumento, seguido pelos argumentos que uma ação de formulário normalmente recebe.
* `initialState`: O valor que você deseja que o estado seja inicialmente. Pode ser qualquer valor serializável. Este argumento é ignorado depois que a ação é invocada pela primeira vez.
* **opcional** `permalink`: Uma string contendo a URL exclusiva 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` é uma [função de servidor](/reference/rsc/server-functions) e o formulário é enviado antes do carregamento do bundle JavaScript, o navegador navegará para a URL de permalink especificada, em vez da URL da página atual. Garanta que o mesmo componente de formulário seja renderizado na página de destino (incluindo a mesma `fn` de ação 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.

{/* TODO T164397693: link to serializable values docs once it exists */}

#### Returns {/*returns*/}
#### Retornos {/*returns*/}

`useActionState` returns an array with the following values:
`useActionState` retorna um array com os seguintes valores:

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.
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. The action can also be called manually within [`startTransition`](/reference/react/startTransition).
3. The `isPending` flag that tells you whether there is a pending Transition.
1. O estado atual. Durante a primeira renderização, ele corresponderá ao `initialState` que você passou. Depois que a ação for invocada, ele corresponderá ao valor retornado pela action.
2. Uma nova ação que você pode passar como a prop `action` para seu componente `form` ou a prop `formAction` para qualquer componente `button` dentro do formulário. A ação também pode ser chamada manualmente dentro de [`startTransition`](/reference/react/startTransition).
3. A flag `isPending` que informa se existe uma Transition pendente.

#### Caveats {/*caveats*/}
#### Ressalvas {/*caveats*/}

* 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.
* 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`.
* Quando usado com um framework que oferece suporte a 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.
* 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 fosse usado diretamente como uma ação de formulário sem usar `useActionState`.

---

## Usage {/*usage*/}
## Uso {/*usage*/}

### Using information returned by a form action {/*using-information-returned-by-a-form-action*/}
### Usando informações retornadas por uma ação de formulário {/*using-information-returned-by-a-form-action*/}

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.
Chame `useActionState` no nível superior do seu componente para acessar o valor de retorno de uma action da última vez que um formulário foi enviado.

```js [[1, 5, "state"], [2, 5, "formAction"], [3, 5, "action"], [4, 5, "null"], [2, 8, "formAction"]]
import { useActionState } from 'react';
@@ -99,15 +98,15 @@ function MyComponent() {
}
```

`useActionState` returns an array with the following items:
`useActionState` retorna um array com os seguintes itens:

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.
2. A <CodeStep step={2}>new action</CodeStep> that you pass to `<form>` as its `action` prop or call manually within `startTransition`.
3. A <CodeStep step={1}>pending state</CodeStep> that you can utilise while your action is processing.
1. O <CodeStep step={1}>estado atual</CodeStep> do formulário, que é inicialmente definido como o <CodeStep step={4}>estado inicial</CodeStep> que você forneceu e, após o formulário ser enviado, é definido como o valor de retorno da <CodeStep step={3}>ação</CodeStep> que você forneceu.
2. Uma <CodeStep step={2}>nova ação</CodeStep> que você passa para o `<form>` como sua prop `action` ou chama manualmente dentro de `startTransition`.
3. Um <CodeStep step={1}>estado pendente</CodeStep> que você pode utilizar enquanto sua ação está processando.

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.
Quando o formulário é enviado, 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.

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.
A <CodeStep step={3}>ação</CodeStep> que você fornece também receberá um novo primeiro argumento, ou seja, o <CodeStep step={1}>estado atual</CodeStep> do formulário. Na primeira vez que o formulário for enviado, este será o <CodeStep step={4}>estado inicial</CodeStep> que você forneceu, enquanto com envios subsequentes, será o valor de retorno da última vez que a action foi chamada. O restante dos argumentos são os mesmos de se `useActionState` não tivesse sido usado.

```js [[3, 1, "action"], [1, 1, "currentState"]]
function action(currentState, formData) {
@@ -116,11 +115,11 @@ function action(currentState, formData) {
}
```

<Recipes titleText="Display information after submitting a form" titleId="display-information-after-submitting-a-form">
<Recipes titleText="Exibir informações após o envio de um formulário" titleId="display-information-after-submitting-a-form">

#### Display form errors {/*display-form-errors*/}
#### Exibir erros de formulário {/*display-form-errors*/}

To display messages such as an error message or toast that's returned by a Server Function, wrap the action in a call to `useActionState`.
Para exibir mensagens como uma mensagem de erro ou toast que é retornado por uma Server Function, envolva a ação em uma chamada para `useActionState`.

<Sandpack>

@@ -182,9 +181,9 @@ form button {

<Solution />

#### Display structured information after submitting a form {/*display-structured-information-after-submitting-a-form*/}
#### Exibir informações estruturadas após o envio de um formulário {/*display-structured-information-after-submitting-a-form*/}

The return value from a Server Function 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.
O valor de retorno de uma Server Function 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.

<Sandpack>

@@ -259,14 +258,14 @@ form button {

</Recipes>

## Troubleshooting {/*troubleshooting*/}
## Solução de problemas {/*troubleshooting*/}

### My action can no longer read the submitted form data {/*my-action-can-no-longer-read-the-submitted-form-data*/}
### Minha action não consegue mais ler os dados do formulário enviado {/*my-action-can-no-longer-read-the-submitted-form-data*/}

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.
Quando você envolve uma action com `useActionState`, ela recebe um argumento extra *como seu primeiro argumento*. Os dados do formulário enviado são, portanto, seu *segundo* argumento em vez de seu primeiro, como seria normalmente. O novo primeiro argumento que é adicionado é o estado atual do formulário.

```js
function action(currentState, formData) {
// ...
}
```
```