1
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?

Next.jsを企業向けに最適化!2025年のアプリ構築術 | エピソード3: GraphQLとApollo Clientの統合

Posted at

目標

  • Next.jsでのGraphQLの利点を理解する。
  • Apollo Clientを使ってGraphQLデータを取得する。
  • ブログのデータソースをSupabaseからGraphQLに切り替える。

1. GraphQLと企業向けアプリ

GraphQLは柔軟なデータ取得を可能にし、企業向けアプリでよく使われます。RESTと異なり、必要なデータだけを取得できるため、効率性が向上します。このエピソードでは、SupabaseをGraphQLに置き換え、Apollo Clientでデータを扱います。


2. Apollo Clientのインストール

GraphQLを利用するために必要なライブラリを導入します。

手順:

ターミナルで以下を実行:

npm install @apollo/client graphql

3. Apollo Clientの設定

Apollo ClientをNext.jsに統合します。

lib/apollo-client.tsの作成:

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

export const client = new ApolloClient({
  link: new HttpLink({
    uri: 'https://jsonplaceholder.ir/graphiql', // サンプルGraphQLエンドポイント
  }),
  cache: new InMemoryCache(),
});

注意

  • 本番では実際のGraphQLサーバー(例:Hasura)を指定。

4. GraphQLデータの取得と表示

ブログの投稿リストをGraphQLで取得します。

app/page.tsxの編集:

'use client';

import { gql } from '@apollo/client';
import { client } from '../lib/apollo-client';
import { useQuery } from '@apollo/client';

const GET_POSTS = gql`
  query GetPosts {
    posts {
      id
      title
      body
    }
  }
`;

export default function Home() {
  const { loading, error, data } = useQuery(GET_POSTS, { client });

  if (loading) return <p className="text-center">読み込み中...</p>;
  if (error) return <p className="text-center">エラー: {error.message}</p>;

  return (
    <div className="min-h-screen flex flex-col items-center bg-gray-100 py-8">
      <h1 className="text-4xl font-bold text-blue-600 mb-8">GraphQLからの投稿</h1>
      <ul className="space-y-4 max-w-2xl w-full">
        {data.posts.map((post) => (
          <li key={post.id} className="bg-white p-4 rounded shadow">
            <a href={`/posts/${post.id}`} className="text-xl font-semibold text-blue-500 hover:underline">
              {post.title}
            </a>
            <p className="text-gray-600">{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

app/posts/[id]/page.tsxの編集:

'use client';

import { gql } from '@apollo/client';
import { client } from '../../../lib/apollo-client';
import { useQuery } from '@apollo/client';

const GET_POST = gql`
  query GetPost($id: ID!) {
    post(id: $id) {
      id
      title
      body
    }
  }
`;

export default function Post({ params }: { params: { id: string } }) {
  const { loading, error, data } = useQuery(GET_POST, {
    client,
    variables: { id: params.id },
  });

  if (loading) return <p className="text-center">読み込み中...</p>;
  if (error) return <p className="text-center">エラー: {error.message}</p>;

  return (
    <div className="max-w-2xl mx-auto p-6">
      <h1 className="text-3xl font-bold text-blue-600 mb-4">{data.post.title}</h1>
      <p className="text-gray-600">{data.post.body}</p>
    </div>
  );
}

注意

  • JSONPlaceholderのGraphQLエンドポイントを使用。実際のプロジェクトでは自前のGraphQLサーバーを推奨。

実践:GraphQLベースのブログ

  • 投稿リスト:GraphQLからデータを取得して表示。
  • 投稿詳細:動的ルートで個別の投稿をGraphQLで取得。

確認

  • npm run devで起動し、http://localhost:3000/posts/1でデータが正しく表示されるか確認。

エピソード3の終了

  • Apollo ClientでGraphQLをNext.jsに統合しました。
  • ブログのデータソースをGraphQLに切り替えました。

次回のエピソード:管理ダッシュボードを作成し、企業向け機能を追加します。


この記事が役に立ったと思ったら、ぜひ「いいね」を押して、ストックしていただければ嬉しいです!次回のエピソードもお楽しみに!

1
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
1
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?