Apollo ClientのLocal-only fieldsについて調べた
Local-only fieldsとは、サーバー側のスキーマには存在せず、クライアントサイドでのみ存在するフィールドのこと
これらは @client ディレクティブを使用して定義される
基本的な使い方
// クライアント側のスキーマ定義 const typeDefs = gql` extend type User { isLoggedIn: Boolean! @client cartItemCount: Int! @client } `; // リゾルバーの定義 const resolvers = { User: { isLoggedIn: () => { return !!localStorage.getItem('token'); }, cartItemCount: () => { return getCartItemCount(); // クライアントサイドのロジック } } };
クエリでの使用例
query GetUserWithLocalFields { user { id # サーバーサイドのフィールド name # サーバーサイドのフィールド isLoggedIn @client # クライアントサイドのフィールド cartItemCount @client # クライアントサイドのフィールド } }
主な用途:
- UI状態の管理
const typeDefs = gql` extend type Query { isModalOpen: Boolean! @client selectedTab: String! @client } `;
- 派生データの計算
const typeDefs = gql` extend type Product { price: Float! taxRate: Float! @client priceWithTax: Float! @client } `; const resolvers = { Product: { taxRate: () => 0.1, priceWithTax: (product) => { return product.price * (1 + 0.1); } } };
- フォーム状態の管理
const typeDefs = gql` extend type Form { isDirty: Boolean! @client validationErrors: [String!] @client } `;
Local-only fieldsの利点
- 統一的なデータアクセス
- サーバーデータとローカルデータを同じGraphQLクエリで取得可能
- 型安全性
- TypeScriptと組み合わせることで、型の恩恵を受けられる
- 宣言的なデータ管理
- データの依存関係を明示的に定義できる
- キャッシュとの統合
- Apollo Clientのキャッシュ機能と統合できる