---
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/19/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")を用いてプリレンダリングできます。

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

> !警告**危険**コンポーネントレベルのgetStaticPropsおよびgetServerSideProps関数に秘密情報や機密情報を含めないでください。これらの機能はクライアントサイドバンドルに含まれています。クライアントバンドルには、クライアント側のコードがインポートを使わなくても、関数が依存するインポートも含まれています。
> 
> これはページレベルのgetStaticPropsやgetServerSideProps機能には影響しません。

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

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

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

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

ComponentPropsServiceはレイアウトサービスデータを巡査し、すべてのレンダリングを確認します。データ取得が必要なコンポーネントを見つけるために、サービスはrendering.componentNamesrc/temp/componentFactoryファイルのコンポーネント登録リストと照らしてそのコンポーネントを監視します。

コンポーネントが関数を定義し、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);