import {Meta} from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/en/functional-basic/Classes/ApiHydration - API Data Hydration'/>

# ApiHydration Class

A class for collecting API data for hydration on the client side during SSR (Server-Side Rendering). It allows the server to capture API responses during the initial render and pass them to the client, preventing redundant network requests when the application initializes in the browser.

> `ApiHydration` is an **auxiliary class**, designed for SSR data management. In most cases, it is recommended to interact with hydration through the global `Api` object using methods like `Api.getHydrationScript()`.

## Key Features

- **SSR Optimization** — reduces the number of requests after the page loads by reusing server-side data.
- **Data Capture** — automatically collects successful API responses marked for global use.
- **HTML Embedding** — generates a safe `<script>` tag with JSON-serialized data for embedding in the document.
- **Client Synchronization** — allows `ApiResponse` to load hydrated data automatically on the client side.

## Methods

### Action

#### `toClient`

Saves the API response for client-side hydration. This method only executes on the server and only for requests where `global` is set to true.

**Parameters:**
- `apiFetch: ApiFetch` — The API request configuration.
- `response: T` — The data payload to be hydrated on the client.

#### `toString`

Returns a string representation of the captured hydration data, wrapped in a safe `<script>` tag with a unique ID.

**Returns:** `string` — The formatted HTML script tag.

### Configuration

- `initResponse(response: ApiResponse): void` — Initializes the `ApiResponse` instance with hydration data if running in a DOM environment.

## Types

#### `ApiHydrationList`
A list of captured API responses for hydration.
- `path: string` — The API endpoint path.
- `method: ApiMethodItem` — The HTTP method used.
- `request: any` — The request payload.
- `response: any` — The server response data.
- `global?: boolean` — Global usage flag.

## Guide: Hydration Mechanics

The following rules and conditions define how the hydration system captures and transfers data between the server and the browser:

- **Global Flag** — only requests where the `global` property is set to `true` in the configuration are captured for hydration.
- **Automatic Handling** — the `global` flag is automatically set to `true` for all `GET` requests. Other methods require explicit manual enabling.
- **Server Execution** — data capture occurs exclusively on the server side (where `isDomRuntime()` is false).
