0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Next.js × GraphQL】query、mutationの書き方について

Posted at

Next.js で GraphQL クエリやミューテーションを行う際に graphql-request ライブラリを使用する方法を説明します。このライブラリは、GraphQL クエリの実行を簡単にするための最小限の GraphQL クライアントです。

基本的なセットアップ

  1. パッケージのインストール: まず graphql-request をプロジェクトに追加します。

    npm install graphql-request
    
  2. GraphQLClient のインポートと設定: クライアントをインポートして、GraphQL サーバーのエンドポイントを設定します。

    import { GraphQLClient } from 'graphql-request';
    
    const client = new GraphQLClient('your-graphql-endpoint');
    

クエリの実行

GraphQL クエリは、通常の文字列として記述されます。graphql-request を使用してこれらのクエリをサーバーに送信できます。

// クエリの例
const query = `
  query GetUser($id: ID!) {
    user(id: $id) {
      name
      email
    }
  }
`;

// クエリの実行
client.request(query, { id: 'ユーザーID' }).then((data) => {
  console.log(data);
});

ミューテーションの実行

ミューテーションもクエリと同様の方法で実行できますが、操作の種類が mutation になります。

// ミューテーションの例
const mutation = `
  mutation UpdateUser($id: ID!, $email: String!) {
    updateUser(id: $id, email: $email) {
      id
      name
      email
    }
  }
`;

// ミューテーションの実行
client.request(mutation, { id: 'ユーザーID', email: 'new-email@example.com' }).then((data) => {
  console.log(data);
});

エラーハンドリング

GraphQL クエリやミューテーションの実行中にエラーが発生した場合、catch ブロックを使用してエラーを捕捉し、適切に処理できます。

client.request(query, { id: 'ユーザーID' })
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

これで、Next.js で graphql-request を使用して GraphQL クエリやミューテーションを実行する基本的な方法を理解できました。API エンドポイントやクエリの詳細は、使用している GraphQL スキーマに応じて異なります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?