Open4
devChallenges-SimpleCoffeeList
面白そうなのでこれやってみる
リポジトリ
構成
APIからコーヒーデータのjson を受け取って表示するだけなので、React + Viteの簡単構成
ディレクトリ構成
/SimleCoffeeList
├── package.json
├── tsconfig.json
├── .eslintrc.cjs
├── public
│ └── index.html
└── src
├── index.tsx
├── api
│ └── fetchData.ts
├── components
│ ├── App.tsx
│ └── page
│ └── Top
│ ├── index.tsx
│ └── styles.css
└── types
└── index.d.ts
実際にコードを書く場所は以下だけ。
- fetchData.ts
- App.tsx
- Top/
fetchData.ts
役割
fetchData.ts
は外部APIからjsonデータをフェッチする
fetchAPI
外部APIのURLは以下なので、fetch APIを使えばOKです!
fetchAPI
コード
import { CoffeeData } from "../types";
export const fetchData = (): Promise<CoffeeData[]> => {
return fetch(
"https://raw.githubusercontent.com/devchallenges-io/web-project-ideas/main/front-end-projects/data/simple-coffee-listing-data.json",
)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.catch((error) => {
console.error("An error occurred while fetching the data: ", error);
return null;
});
};
ポイント
- fetchAPIはネットワークエラーの時のみ、例外を返す為、エラーチェックは
response.ok
で行う - fetchAPIはHTTP レスポンス全体がレスポンスとして返ってくるので、jsonを抽出するには
response.json()
する
App.tsx
役割
- fetchAPIを使ってjsonデータを取得する
- Topコンポーネントにデータを渡す
上位のコンポーネントでページ単位で区切ったTopコンポーネントにjsonデータを受け渡しているだけです。
import { fetchData } from "../api/fetchData.ts";
import { Top } from "./page/Top";
import { CoffeeData } from "../types";
import { useEffect, useState } from "react";
export const App = () => {
const [data, setData] = useState<CoffeeData[]>([]);
useEffect(() => {
fetchData().then((fetchedData) => {
setData(fetchedData);
});
}, []);
return (
<div>
<Top data={data} />
</div>
);
};
ポイント
fetchData()
はPromise
を返す非同期処理である。Reactでは非同期処理などの副作用はuseEffect
を使ってコンポーネントの状態として保持する