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です!

https://raw.githubusercontent.com/devchallenges-io/web-project-ideas/main/front-end-projects/data/simple-coffee-listing-data.json

fetchAPI
https://developer.mozilla.org/ja/docs/Web/API/Fetch_API/Using_Fetch

コード

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を使ってコンポーネントの状態として保持する