Next.js で GraphQL クライアント Apolloクライアントを使用する

● 1. サンプルの「GraphQLクエリ」と「結果」を確認しておく

URL
http://snowtooth.moonhighway.com/

エンドポイントURL

https://countries.trevorblades.com

GraphQLクエリ

query {
  countries{
    code
    name
    emoji
  }
}

こちらの「エンドポイントURL」「GraphQLクエリ」を入力して ▶︎のボタンをクリックするとGraphQLクエリーが実行されます


● 2. apolloクライアントのインストール

開発しているアプリケーションの一番上の階層からnpmでインストールします

npm install @apollo/client graphql

● 3. apolloクライアントクラスの作成

apollo-client.js

import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  uri: 'https://countries.trevorblades.com',            // 今は直接設定していますが .env から参照しましょう。
  cache: new InMemoryCache(),
});

export default client;

● 4. GraphQLから取り込んだデータを表示したいコンポーネントで次のように追加する

/pages/index.js

import { gql } from "@apollo/client";
import client from "../apollo-client";

SSG (Static Site Generation)用の getStaticProps() 関数を作成する
/pages/index.js

// getStaticProps ( for SSG (Static Site Generation) )
//   getStaticPathsは(本番環境)ビルド時に実行されます / (開発環境)リクエスト毎に実行されます
export async function getStaticProps() {
  const { data } = await client.query({
    query: gql`
query {
  countries{
    code
    name
    emoji
  }
}
    `,
  });
  return {
    props: {
      countries: data.countries.slice(0, 4),
    },
 };
}

/pages/index.js の JSXで表示する

export default function Home({ countries }) {
      {countries.map((v) => (
        <div key={v.code} style={{ display:'flex' }}>
          <h1 style={{ lineHeight:'100px' }}>{v.name}</h1>
          <div style={{ fontSize:'100px' }}>
            {v.emoji}
          </div>
        </div>
      ))}

これで該当ページを表示すると次のような表示となります

以上です。


● getStaticProps , getStaticPaths , getServerSideProps について

https://bit.ly/3oCOn4L

getStaticProps(静的生成): ビルド時にデータ取得する
getStaticPaths(静的生成): データに基づきプリレンダリングする動的ルートを特定する
getServerSideProps(サーバーサイドレンダリング): リクエストごとにデータを取得する


● VS Code の拡張機能「Apollo GraphQL」のインストールして開発速度をアップさせる

https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo

[GraphQL] TypeScript+VSCode+Apolloで最高のDXを手に入れよう | DevelopersIO


● GraphQL Playground for Chrome

https://chrome.google.com/webstore/detail/graphql-playground-for-ch/kjhjcgclphafojaeeickcokfbhlegecd/related?hl=ja


● Apollo Client Devtools for Chrome

https://chrome.google.com/webstore/detail/apollo-client-devtools/jdkknkkbebbapilgoeccciglkfbmbnfm/related

Google Chromeの拡張機能 Apollo Client Devtools でできること(引用 : https://bit.ly/3pmP4je

– GraphiQLをその場で実行する(本来であればAPIサーバと別のポートでGraphiQLサーバを立ち上げて、ブラウザでそこにアクセスして利用します)
– JavaScriptから発行されたクエリのログの確認、クエリの編集・再発行
– apollo-link-stateでキャッシュに書き込んだ値の確認(apolloはクエリのレスポンスを勝手にキャッシュしてくれるのですが、その内容も確認できます)

初めて Apollo Client を使うことになったらキャッシュについて知るべきこと - WASD TECH BLOG

・取得するフィールドに id は必ず含める
・更新処理のときは Mutation のレスポンスでオブジェクトのキャッシュを更新する
・作成、削除処理のときは refetchQueries などを使い配列のキャッシュを更新する
・画面表示のたびに最新のデータを表示したければ fetchPolicy: "cache-and-network" を使う

fetchPolicy の種類

https://www.apollographql.com/docs/react/data/queries/

Name Description
cache-first

Apollo Client first executes the query against the cache. If all requested data is present in the cache, that data is returned. Otherwise, Apollo Client executes the query against your GraphQL server and returns that data after caching it.

Prioritizes minimizing the number of network requests sent by your application.

This is the default fetch policy.

cache-only

Apollo Client executes the query only against the cache. It never queries your server in this case.

A cache-only query throws an error if the cache does not contain data for all requested fields.

cache-and-network

Apollo Client executes the full query against both the cache and your GraphQL server. The query automatically updates if the result of the server-side query modifies cached fields.

Provides a fast response while also helping to keep cached data consistent with server data.

network-only

Apollo Client executes the full query against your GraphQL server, without first checking the cache. The query's result is stored in the cache.

Prioritizes consistency with server data, but can't provide a near-instantaneous response when cached data is available.

no-cache

Similar to network-only, except the query's result is not stored in the cache.

standby

Uses the same logic as cache-first, except this query does not automatically update when underlying field values change. You can still manually update this query with refetch and updateQueries.

参考 : ApolloのFetchPoliciesを理解する - Qiita

添付ファイル1
No.2084
12/09 16:10

edit

添付ファイル