> ## Documentation Index
> Fetch the complete documentation index at: https://inertiajs-vi.tuantq.online/llms.txt
> Use this file to discover all available pages before exploring further.

# Dữ liệu dùng chung

<Warning>Bạn đang xem tài liệu Inertia.js v2. Inertia.js v3 đã được phát hành và hiện là phiên bản mặc định. Hãy xem [hướng dẫn nâng cấp](/v3/getting-started/upgrade-guide) để bắt đầu.</Warning>

Đôi khi bạn cần truy cập một số dữ liệu cụ thể trên nhiều trang trong ứng dụng. Ví dụ, bạn có thể cần hiển thị người dùng hiện tại trong header của website. Việc truyền thủ công dữ liệu này trong từng response trên toàn ứng dụng khá bất tiện. May mắn là có một lựa chọn tốt hơn: dữ liệu dùng chung.

## Chia sẻ dữ liệu

Tất cả adapter phía máy chủ của Inertia đều cung cấp một cách để đưa dữ liệu dùng chung vào mọi request. Việc này thường được thực hiện bên ngoài controller. Dữ liệu dùng chung sẽ tự động được merge với page props mà controller cung cấp.

Trong ứng dụng Laravel, việc này thường được xử lý bởi middleware `HandleInertiaRequests`, được tự động cài đặt khi cài [server-side adapter](/v2/installation/server-side-setup#middleware).

```php theme={null}
class HandleInertiaRequests extends Middleware
{
    public function share(Request $request)
    {
        return array_merge(parent::share($request), [
            // Synchronously...
            'appName' => config('app.name'),

            // Lazily...
            'auth.user' => fn () => $request->user()
                ? $request->user()->only('id', 'name', 'email')
                : null,
        ]);
    }
}
```

Ngoài ra, bạn có thể chia sẻ dữ liệu thủ công bằng phương thức `Inertia::share`.

```php theme={null}
use Inertia\Inertia;

// Synchronously...
Inertia::share('appName', config('app.name'));

// Lazily...
Inertia::share('user', fn (Request $request) => $request->user()
    ? $request->user()->only('id', 'name', 'email')
    : null
);
```

Nên sử dụng dữ liệu dùng chung một cách tiết chế vì toàn bộ dữ liệu dùng chung được gửi kèm trong mọi response.

Page props và dữ liệu dùng chung được merge với nhau, vì vậy hãy namespace dữ liệu dùng chung phù hợp để tránh xung đột.

## Chia sẻ once props

Bạn có thể chia sẻ dữ liệu chỉ được resolve một lần và được phía client ghi nhớ qua các lần điều hướng tiếp theo bằng [once props](/v2/data-props/once-props).

```php theme={null}
class HandleInertiaRequests extends Middleware
{
    public function share(Request $request)
    {
        return array_merge(parent::share($request), [
            'countries' => Inertia::once(fn () => Country::all()),
        ]);
    }
}
```

Ngoài ra, bạn có thể định nghĩa riêng phương thức `shareOnce()` trong middleware. Middleware sẽ đánh giá cả `share()` và `shareOnce()`, sau đó gộp kết quả.

```php theme={null}
class HandleInertiaRequests extends Middleware
{
    public function shareOnce(Request $request): array
    {
        return array_merge(parent::shareOnce($request), [
            'countries' => fn () => Country::all(),
        ]);
    }
}
```

Bạn cũng có thể chia sẻ once props thủ công bằng phương thức `Inertia::shareOnce()`.

```php theme={null}
Inertia::shareOnce('countries', fn () => Country::all());
```

## Truy cập dữ liệu dùng chung

Sau khi chia sẻ dữ liệu ở phía máy chủ, bạn có thể truy cập dữ liệu đó trong bất kỳ trang hoặc component nào. Sau đây là ví dụ cách truy cập dữ liệu dùng chung trong một layout component.

<CodeGroup>
  ```vue Vue icon="vuejs" theme={null}
  <script setup>
  import { computed } from "vue";
  import { usePage } from "@inertiajs/vue3";

  const page = usePage();

  const user = computed(() => page.props.auth.user);
  </script>

  <template>
    <main>
      <header>You are logged in as: {{ user.name }}</header>
      <article>
        <slot />
      </article>
    </main>
  </template>
  ```

  ```jsx React icon="react" theme={null}
  import { usePage } from "@inertiajs/react";

  export default function Layout({ children }) {
    const { auth } = usePage().props;

    return (
      <main>
        <header>You are logged in as: {auth.user.name}</header>
        <article>{children}</article>
      </main>
    );
  }
  ```

  ```svelte Svelte icon="s" theme={null}
  <script>
      import { page } from '@inertiajs/svelte'
  </script>

  <main>
      <header>
          You are logged in as: {$page.props.auth.user.name}
      </header>
      <article>
          <slot />
      </article>
  </main>
  ```
</CodeGroup>

## TypeScript

Bạn có thể cấu hình kiểu của shared props trên toàn cục bằng [declaration merging của TypeScript](/v2/advanced/typescript#shared-page-props).

## Flash data

Với các thông báo chỉ xuất hiện một lần như toast hoặc thông báo thành công, bạn có thể dùng [flash data](/v2/data-props/flash-data). Khác với shared data, flash data không được lưu trong history state của trình duyệt, vì vậy chúng sẽ không xuất hiện lại khi người dùng điều hướng qua lịch sử.

***

## Tài liệu chính thức

Bài dịch này được đối chiếu từ [tài liệu Inertia.js v2 chính thức](https://inertiajs.com/docs/v2/data-props/shared-data). Nếu có khác biệt do phiên bản hoặc cập nhật mới, hãy ưu tiên tài liệu chính thức làm nguồn tham chiếu.
