urql
https://github.com/urql-graphql/urql/raw/main/packages/site/src/assets/sidebar-badge.svg
https://commerce.nearform.com/open-source/urql/docs/
概要
GraphQL クライアントライブラリ
Apollo Client や Relay と比べると後発で、軽量かつシンプル
軽量
table:_
urql Apollo Relay
10kB (11kB with bindings) ~50kB (55kB with React hooks) 45kB (66kB with bindings)
https://arc.net/l/quote/zcleeiki
シンプル
https://commerce.nearform.com/open-source/urql/docs/comparison/#caching-and-state
Apollo Client や Relay では、クエリ結果を id と __typename をキーに 正規化 してキャッシュする
正規化キャッシュ
Mutation によるデータ更新時も、キャッシュ上のどのデータを更新すべきかを知ることができる
これにより、ネットワークアクセスを介さずにクライアントの状態を更新できる
一方、urql では ドキュメントキャッシュ と呼ばれる戦略をデフォルトで採用している
urql is the only library that provides Offline Support out of the box as part of Graphcache's feature set.
https://arc.net/l/quote/erxnynaa
正規化キャッシュも可能
Once you need the same features that you'll find in Relay and Apollo, it's possible to migrate to Graphcache.
https://arc.net/l/quote/rhtumtzz
ドキュメントキャッシュ
Mutation によるデータ更新後、同一 __typename を持つクエリのキャッシュを破棄して再取得する
ネットワークアクセスの頻度は高くなるが、更新したデータを画面上に表示する必要がないアプリケーションの場合、正規化キャッシュ のように高度なキャッシュ戦略は不要
セットアップ(React)
インストール
code:sh
$ npm install --save urql
Client インスタンスの生成
https://commerce.nearform.com/open-source/urql/docs/api/core/#client
クエリの発行やキャッシュを管理する
code:src/main.tsx
import { cacheExchange, Client, fetchExchange } from "urql";
const client = new Client({
url: "http://localhost:4000/graphql",
exchanges: cacheExchange, fetchExchange,
});
url: GraphQL サーバの URL
exchanges: urql における ミドルウェア や プラグイン に該当する機能
https://commerce.nearform.com/open-source/urql/docs/architecture/#the-exchanges
Context API の利用
生成した Client を Context API を介して取得できるように、urql から提供されている <Provider> を用いる
code:src/main.tsx
import { Provider } from "urql";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<Provider value={client}>
<App />
</Provider>
</StrictMode>,
);
クエリの呼び出し
Query
useQuery を用いる
https://commerce.nearform.com/open-source/urql/docs/api/urql/#usequery
code:tsx
import { gql, useQuery } from "urql";
const result = useQuery({
query: gql`
query posts($tags: String!) {
posts(tags: $tags) {
title
body
author {
name
}
}
}
`,
variables: { tags },
});
const { data, fetching, error } = result;
戻り値として以下を返す
data: クエリの結果
warning.icon data は any なので、GraphQL-Codegen を用いて型定義を生成する必要がある
error: エラー
fetching: 取得中か
#JavaScript #GraphQL #TypeScript