概要
-
Reactコンポーネントで外部APIを呼び出す方法として、useEffectとfetchを活用する方法をまとめた - 最小構成での書き方から、実践的な活用例(JSONPlaceholder / GitHub API / CoinMarketCap API)までを紹介
-
TypeScriptによる型定義で、安全で明確なデータ取得を実現する構成とした
実施条件
- React + TypeScript プロジェクトが構築済みであること
- 外部APIにアクセスできるネットワーク環境が整っていること
-
npmで依存関係を追加可能な構成であること - CoinMarketCapのAPIキー(無料で取得可)を持っていること
参考リンク
[React][TypeScript] useEffectの基本的な使い方
MDN fetch() 解説
JSONPlaceholder
GitHub REST API
CoinMarketCap API
環境
| ツール | バージョン | 目的 |
|---|---|---|
| Node.js | 18.x 以上 | Reactアプリ実行環境 |
| React | 18.x または 19.x | UI コンポーネントの構築 |
| TypeScript | 5.x 以上 | 型定義による安全な開発 |
| fetch API | ブラウザ標準搭載 | API 通信処理 |
型定義
// 基本構文用
type MessageResponse = {
message: string;
};
// 活用例1
type Post = {
userId: number;
id: number;
title: string;
body: string;
};
// 活用例2
type GitHubUser = {
login: string;
avatar_url: string;
html_url: string;
};
// 活用例3
type CoinMarketData = {
data: {
[symbol: string]: {
name: string;
quote: {
USD: {
price: number;
};
};
};
};
};
関数コンポーネントにおける基本構造
- importセクション
- 型定義セクション
- 関数定義セクション
- 状態管理セクション
- イベントハンドラーセクション(今回は使用しない)
- 副作用処理セクション
- JSX構築セクション
基本構文:最小のfetch使用例
// importセクション
import React, { useEffect, useState } from 'react';
// 型定義セクション
type MessageResponse = {
message: string;
};
// 関数定義セクション
const SimpleFetch: React.FC = () => {
// 状態管理セクション
const [message, setMessage] = useState<string>('');
// 副作用処理セクション
useEffect(() => {
fetch('https://api.example.com/hello') // ← 実際のAPIに置き換えてください
.then((res) => res.json())
.then((data: MessageResponse) => {
setMessage(data.message);
});
}, []);
// JSX構築セクション
return <p>{message}</p>;
};
export default SimpleFetch;
活用例
1. 投稿のタイトルを取得する(JSONPlaceholder)
// importセクション
import React, { useEffect, useState } from 'react';
// 型定義セクション
type Post = {
userId: number;
id: number;
title: string;
body: string;
};
// 関数定義セクション
const FetchPostTitle: React.FC = () => {
// 状態管理セクション
const [title, setTitle] = useState<string>('');
// 副作用処理セクション
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((res) => res.json())
.then((data: Post) => {
setTitle(data.title);
});
}, []);
// JSX構築セクション
return <h1>{title}</h1>;
};
export default FetchPostTitle;
2. GitHubユーザーのプロフィールを表示する
// importセクション
import React, { useEffect, useState } from 'react';
// 型定義セクション
type GitHubUser = {
login: string;
avatar_url: string;
html_url: string;
};
// 関数定義セクション
const GitHubProfile: React.FC = () => {
// 状態管理セクション
const [user, setUser] = useState<GitHubUser | null>(null);
// 副作用処理セクション
useEffect(() => {
fetch('https://api.github.com/users/octocat')
.then((res) => res.json())
.then((data: GitHubUser) => {
setUser(data);
});
}, []);
// JSX構築セクション
if (!user) return <p>読み込み中...</p>;
return (
<div>
<h2>{user.login}</h2>
<img src={user.avatar_url} alt="avatar" width={100} />
<p>
<a href={user.html_url} target="_blank" rel="noopener noreferrer">
GitHub プロフィールを見る
</a>
</p>
</div>
);
};
export default GitHubProfile;
3. CoinMarketCap APIでビットコインの価格を取得する
// importセクション
import React, { useEffect, useState } from 'react';
// 型定義セクション
type CoinMarketData = {
data: {
[symbol: string]: {
name: string;
quote: {
USD: {
price: number;
};
};
};
};
};
// 関数定義セクション
const CoinPrice: React.FC = () => {
// 状態管理セクション
const [price, setPrice] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
// 副作用処理セクション
useEffect(() => {
const fetchPrice = async () => {
try {
const res = await fetch(
'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC',
{
headers: {
'X-CMC_PRO_API_KEY': 'YOUR_API_KEY_HERE', // ← ご自身のAPIキーに置き換えてください
},
}
);
const data: CoinMarketData = await res.json();
const btcPrice = data.data.BTC.quote.USD.price;
setPrice(btcPrice);
} catch (err) {
setError('データ取得に失敗しました');
}
};
fetchPrice();
}, []);
// JSX構築セクション
if (error) return <p>{error}</p>;
if (price === null) return <p>読み込み中...</p>;
return <h2>Bitcoin価格: ${price.toFixed(2)}</h2>;
};
export default CoinPrice;
💡 注意:CoinMarketCapの無料APIキーはこちらから取得できます。
fetchプロセスの流れ
-
useEffectにより、コンポーネントの初回レンダリング時に処理が発火 -
fetchで指定したAPIにHTTPリクエストを送信 - レスポンスを
.json()によってJSONとして解析 -
setStateでステートを更新し、UIを再描画
おわりに
useEffectとfetchの組み合わせにより、React内で簡単に外部データを取得できます。
CoinMarketCapのような外部サービスも、APIキーさえあればすぐに活用でき、リアルタイムデータを表示するアプリ開発にも応用できます。
次回は、async/await + try/catch 構文でのエラーハンドリング付きバージョンや、ローディングUIの実装方法なども取り上げます。