LoginSignup
15
2

More than 3 years have passed since last update.

Apollo Client 3で追加された機能

Last updated at Posted at 2020-07-15

はじめに

Apollo Client 3がリリースされました。AC2からの変更点としては

  • これまで別々のパッケージから呼び出していた各モジュールが @apollo/client に集約された
  • typePoliciesReactive Variable など、ローカルのステート管理機能が拡充された

といった感じです。実際にAC3を試してみると、今までメインで使っていた機能の使い方はほぼ変わらず、特に上記ローカルのステート管理周辺が改善された印象です。今回はtypePoliciesとReactive Variableのご紹介をします。

typePolicies

ローカルのキャッシュ(Apollo ClientのInMemoryCacheと呼ばれる)において、GraphQLスキーマの各タイプをどう扱うかをtypePoliciesで定義できるようになりました。また、バージョン2まで@clientとローカルリゾルバで行っていた同様の処理を扱うことができます(AC3からLocal Resolverはdeprecatedとなっています)。

呼び出し時(read


const cache = new InMemoryCache({
  typePolicies: {
    Person: {
      fields: {
        name: {
          read(name) {
            return name.toUpperCase();
          }
        }
      },
    },
  },
})

// クエリの例
export const GET_PERSON = gql`
  query getPersion($id: String!) {
    person(id: $id) {
      id
      name
      age   
    }
  }
`

レンダーされるnameが大文字に。

更新時(merge


const cache = new InMemoryCache({
  typePolicies: {
    Agenda: {
      fields: {
        tasks: {
          merge(existing = [], incoming: any[]) {
            return [...existing, ...incoming];
          },
        },
      },
    },
  },
})

上記はキャッシュに存在する配列とサーバーから送られる配列の値をマージする例。

Reactive Variable

上記typePoliciesのreadからReactive Variableを参照すれば、Reactive Variableを更新することでキャッシュが返す値を更新することが可能。


import { makeVar } from '@apollo/client'

const cartItems = makeVar([])

// 値のセット
cartItems([100, 101, 102])

// 値の取得
const currentCartItems = cartItems()

まとめ

今回はApollo Client 3で追加されたtypePoliciesとReactive Variableを紹介しました。サンプルはこちら

References

15
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
2