---
title: "JSS Next.jsアプリにおけるコンポーネントレベルのデータ取得"
slug: "component-level-data-fetching-in-jss-next-js-apps"
abstract: "JSS Next.jsアプリがコンポーネントレベルのデータをどのように取得し、それにアクセスできるかの概要"
---
# JSS Next.jsアプリにおけるコンポーネントレベルのデータ取得

Next.jsは、各レンダリング [フォームごとにページレベルのデータ取得戦略](https://doc.sitecore.com/xp/ja/developers/hd/21/sitecore-headless-development/prerendering-methods-and-data-fetching-strategies-in-jss-next-js-apps.html "Prerendering methods and data fetching strategies in JSS Next.js apps")を用いて、ビルド時や各リクエスト時にページをプリレンダリングできます。

コンポーネントレベルで特定のデータを取得したい場合、ページレベルのデータ取得に似た仕組みを使い、静的生成(SG)用のgetStaticPropsやサーバー側レンダリング用のgetServerSideProps関数(SSR)を実装・エクスポートすることができます。

> !注コンポーネントレベルのgetStaticPropsやgetServerSideProps関数に秘密情報や機密情報を含めると、その情報は開発モードでクライアントサイドのバンドルにのみ含まれます。

JSSアプリにおけるコンポーネントレベルのデータフェッチのデモは、以下のビデオをご覧ください。

:::youtube{id="Py1l4PPp2H0"}

> !注**XM Cloudは現在SitecoreAIです**エンジニアリング資産が更新されている間、一部のコード例、画像、UIラベルは引き続きXM Cloudを使用する場合があります。

> !重要コンポーネントレベルのデータ取得はエラーページで動作することを想定していません。

## コンポーネントPropsServiceクラス

SitecorePagePropsFactoryクラスはComponentPropsServiceクラスのインスタンスを使用し、どのコンポーネントがデータ取得を必要とするかを特定するのに役立ちます。ComponentPropsServiceクラスはNPMパッケージ@sitecore-jss/sitecore-jss-nextjsによって提供されます。

ComponentPropsServiceクラスは以下のパラメータを受け入れます。

-   moduleFactory - componentName 引数を用いてNext.jsコンポーネントモジュールを返す関数。 moduleFactory 関数の定義は src/temp/componentBuilder ファイルにあります。存在しない場合は、 scripts/bootstrap.tsを実行して生成します。
-   layoutData - ページのレイアウトサービスデータ。
-   context - Next.jsのSSGまたはSSRコンテキスト。

ComponentPropsServiceクラスはレイアウトサービスデータを巡査し、すべてのレンダリングを確認します。データ取得が必要なコンポーネントを見つけるために、サービスはsrc/temp/componentBuilderファイルのコンポーネント登録リストに対してrendering.componentNameプロパティを使ってコンポーネントを監視します。

コンポーネントが関数を定義し、getStaticPropsまたはgetServerSidePropsをエクスポートすると、ComponentPropsServiceクラスはその関数を実行します。すべての副効果を適用した後、コンポーネントデータを{ rendering.uid: data }の形式でcomponentPropsオブジェクトに保存します。

例えば、次のコンポーネントはデータフェッチ関数を定義し、レンダリングUIDを使ってコンポーネントプロップのコンテキストからインポートされたコンポーネントプロップを表示します。

> !注この例のコンポーネントには、getStaticProps関数とgetServerSideProps関数の両方の実装が含まれています。実際のコンポーネントでは、選択するレンダリングモードに応じて、そのうち1つだけを定義する必要があります。

import {
 Text,
 RichText,
 Field,
 GetServerSideComponentProps,
 GetStaticComponentProps,
 withDatasourceCheck,
 useComponentProps,
} from '@sitecore-jss/sitecore-jss-nextjs';
import { ComponentParams, ComponentRendering } from '@sitecore-jss/sitecore-jss-nextjs';

type ComponentProps = {
 rendering: ComponentRendering;
 params: ComponentParams;
};

type ContentBlockProps = ComponentProps & {
 fields: {
 heading: Field<string>;
 content: Field<string>;
 };
};

type Post = {
 title: string;
 body: string;
};

const ContentBlock = (props: ContentBlockProps): JSX.Element => {
 const { fields, rendering } = props;

 // Component-level fetched data is stored by rendering.uid
 const post = useComponentProps<Post>(rendering.uid);

 return (
 <div className="contentBlock">
 <Text tag="h2" className="contentTitle" field={fields.heading} />
 <RichText className="contentDescription" field={fields.content} />

 {/\* Demonstrate using fetched data returned by getStaticProps/getServerSideProps \*/}
 {post && (
 <section className="contentPost">
 <h3>{post.title}</h3>
 <p>{post.body}</p>
 </section>
 )}
 </div>
 );
};

const fetchPost = () =>
 fetch('https://jsonplaceholder.typicode.com/posts/1').then((res) => res.json());

// Note: Define only ONE of these in a real component, based on rendering mode.
export const getStaticProps: GetStaticComponentProps = async (rendering, layoutData, context) => {
 const post = await fetchPost();
 return post;
};

export const getServerSideProps: GetServerSideComponentProps = async (rendering, layoutData) => {
 const post = await fetchPost();
 return post;
};

export default withDatasourceCheck()<ContentBlockProps>(ContentBlock);