Skip to content
Open
Changes from all commits
Commits
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
78 changes: 39 additions & 39 deletions src/content/reference/react-dom/hooks/useFormStatus.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: useFormStatus

<Intro>

`useFormStatus` is a Hook that gives you status information of the last form submission.
`useFormStatus` — это хук, который предоставляет информацию о статусе последней отправки формы.

```js
const { pending, data, method, action } = useFormStatus();
Expand All @@ -16,11 +16,11 @@ const { pending, data, method, action } = useFormStatus();

---

## Reference {/*reference*/}
## Справочник {/*reference*/}

### `useFormStatus()` {/*use-form-status*/}

The `useFormStatus` Hook provides status information of the last form submission.
Хук `useFormStatus` предоставляет информацию о статусе последней отправки формы.

```js {5},[[1, 6, "status.pending"]]
import { useFormStatus } from "react-dom";
Expand All @@ -40,42 +40,42 @@ export default function App() {
}
```

To get status information, the `Submit` component must be rendered within a `<form>`. The Hook returns information like the <CodeStep step={1}>`pending`</CodeStep> property which tells you if the form is actively submitting.
Чтобы получить информацию о статусе, компонент `Submit` должен быть отрисован внутри `<form>`. Хук возвращает такую информацию, как свойство <CodeStep step={1}>`pending`</CodeStep>, которое указывает, происходит ли в данный момент отправка формы.

In the above example, `Submit` uses this information to disable `<button>` presses while the form is submitting.
В приведенном выше примере `Submit` использует эту информацию, чтобы отключить нажатие на `<button>` во время отправки формы.

[See more examples below.](#usage)
[См. больше примеров ниже.](#usage)

#### Parameters {/*parameters*/}
#### Параметры {/*parameters*/}

`useFormStatus` does not take any parameters.
`useFormStatus` не принимает никаких параметров.

#### Returns {/*returns*/}
#### Возвращает {/*returns*/}

A `status` object with the following properties:
Объект `status` со следующими свойствами:

* `pending`: A boolean. If `true`, this means the parent `<form>` is pending submission. Otherwise, `false`.
* `pending`: Булево значение. Если `true`, это означает, что родительская форма `<form>` находится в состоянии ожидания отправки. В противном случае — `false`.

* `data`: An object implementing the [`FormData interface`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) that contains the data the parent `<form>` is submitting. If there is no active submission or no parent `<form>`, it will be `null`.
* `data`: Объект, реализующий [`FormData interface`](https://developer.mozilla.org/en-US/docs/Web/API/FormData), содержащий данные, которые отправляет родительская форма `<form>`. Если активной отправки нет или родительской формы `<form>` нет, значение будет `null`.

* `method`: A string value of either `'get'` or `'post'`. This represents whether the parent `<form>` is submitting with either a `GET` or `POST` [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). By default, a `<form>` will use the `GET` method and can be specified by the [`method`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method) property.
* `method`: Строковое значение `'get'` или `'post'`. Это указывает, отправляется ли родительская форма `<form>` с использованием метода [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) `GET` или `POST`. По умолчанию форма `<form>` использует метод `GET`, который можно указать с помощью свойства [`method`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method).

[//]: # (Link to `<form>` documentation. "Read more on the `action` prop on `<form>`.")
* `action`: A reference to the function passed to the `action` prop on the parent `<form>`. If there is no parent `<form>`, the property is `null`. If there is a URI value provided to the `action` prop, or no `action` prop specified, `status.action` will be `null`.
* `action`: Ссылка на функцию, переданную в свойство `action` родительской формы `<form>`. Если родительской формы `<form>` нет, свойство будет `null`. Если в свойстве `action` указано значение URI или свойство `action` не указано, `status.action` будет `null`.

#### Caveats {/*caveats*/}
#### Ограничения {/*caveats*/}

* The `useFormStatus` Hook must be called from a component that is rendered inside a `<form>`.
* `useFormStatus` will only return status information for a parent `<form>`. It will not return status information for any `<form>` rendered in that same component or children components.
* Хук `useFormStatus` должен вызываться из компонента, который отрисован внутри `<form>`.
* `useFormStatus` будет возвращать информацию о статусе только для родительской формы `<form>`. Он не будет возвращать информацию о статусе для любой формы `<form>`, отрисованной в том же компоненте или в дочерних компонентах.

---

## Usage {/*usage*/}
## Использование {/*usage*/}

### Display a pending state during form submission {/*display-a-pending-state-during-form-submission*/}
To display a pending state while a form is submitting, you can call the `useFormStatus` Hook in a component rendered in a `<form>` and read the `pending` property returned.
### Отображение состояния ожидания во время отправки формы {/*display-a-pending-state-during-form-submission*/}
Чтобы отобразить состояние ожидания во время отправки формы, вы можете вызвать хук `useFormStatus` в компоненте, отрисованном внутри `<form>`, и прочитать возвращаемое свойство `pending`.

Here, we use the `pending` property to indicate the form is submitting.
Здесь мы используем свойство `pending`, чтобы указать, что форма отправляется.

<Sandpack>

Expand Down Expand Up @@ -110,34 +110,34 @@ export async function submitForm(query) {
await new Promise((res) => setTimeout(res, 1000));
}
```
</Sandpack>
</Sandpack>

<Pitfall>

##### `useFormStatus` will not return status information for a `<form>` rendered in the same component. {/*useformstatus-will-not-return-status-information-for-a-form-rendered-in-the-same-component*/}
##### `useFormStatus` не вернет информацию о статусе для `<form>`, отрисованной в том же компоненте. {/*useformstatus-will-not-return-status-information-for-a-form-rendered-in-the-same-component*/}

The `useFormStatus` Hook only returns status information for a parent `<form>` and not for any `<form>` rendered in the same component calling the Hook, or child components.
Хук `useFormStatus` возвращает информацию о статусе только для родительской формы `<form>`, а не для любой формы `<form>`, отрисованной в том же компоненте, который вызывает хук, или в дочерних компонентах.

```js
function Form() {
// 🚩 `pending` will never be true
// useFormStatus does not track the form rendered in this component
// 🚩 `pending` никогда не будет true
// useFormStatus не отслеживает форму, отрисованную в этом компоненте
const { pending } = useFormStatus();
return <form action={submit}></form>;
}
```

Instead call `useFormStatus` from inside a component that is located inside `<form>`.
Вместо этого вызывайте `useFormStatus` из компонента, который находится внутри `<form>`.

```js
function Submit() {
// ✅ `pending` will be derived from the form that wraps the Submit component
const { pending } = useFormStatus();
// ✅ `pending` будет получен из формы, которая оборачивает компонент Submit
const { pending } = useFormStatus();
return <button disabled={pending}>...</button>;
}

function Form() {
// This is the <form> `useFormStatus` tracks
// Это <form>, который отслеживает `useFormStatus`
return (
<form action={submit}>
<Submit />
Expand All @@ -148,11 +148,11 @@ function Form() {

</Pitfall>

### Read the form data being submitted {/*read-form-data-being-submitted*/}
### Чтение отправляемых данных формы {/*read-form-data-being-submitted*/}

You can use the `data` property of the status information returned from `useFormStatus` to display what data is being submitted by the user.
Вы можете использовать свойство `data` информации о статусе, возвращаемой `useFormStatus`, чтобы отобразить, какие данные отправляются пользователем.

Here, we have a form where users can request a username. We can use `useFormStatus` to display a temporary status message confirming what username they have requested.
Здесь у нас есть форма, где пользователи могут запросить имя пользователя. Мы можем использовать `useFormStatus`, чтобы отобразить временное сообщение о статусе, подтверждающее, какое имя пользователя они запросили.

<Sandpack>

Expand Down Expand Up @@ -215,16 +215,16 @@ button {

```

</Sandpack>
</Sandpack>

---

## Troubleshooting {/*troubleshooting*/}
## Устранение неполадок {/*troubleshooting*/}

### `status.pending` is never `true` {/*pending-is-never-true*/}
### `status.pending` никогда не равен `true` {/*pending-is-never-true*/}

`useFormStatus` will only return status information for a parent `<form>`.
`useFormStatus` будет возвращать информацию о статусе только для родительской формы `<form>`.

If the component that calls `useFormStatus` is not nested in a `<form>`, `status.pending` will always return `false`. Verify `useFormStatus` is called in a component that is a child of a `<form>` element.
Если компонент, вызывающий `useFormStatus`, не вложен в `<form>`, `status.pending` всегда будет возвращать `false`. Убедитесь, что `useFormStatus` вызывается в компоненте, который является дочерним элементом `<form>`.

`useFormStatus` will not track the status of a `<form>` rendered in the same component. See [Pitfall](#useformstatus-will-not-return-status-information-for-a-form-rendered-in-the-same-component) for more details.
`useFormStatus` не будет отслеживать статус формы `<form>`, отрисованной в том же компоненте. Подробнее см. [Ограничение](#useformstatus-will-not-return-status-information-for-a-form-rendered-in-the-same-component).
Loading