1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】 #6 金額計算機アプリを作成

Last updated at Posted at 2024-12-31

はじめに

現在、Reactを習得するために、23種類のReactアプリ開発に取り組んでいます。
今回はその第6弾として、Reactで金額計算機アプリを作成しました。

要件

以下の要件を満たすことを目指しています:

  • ユーザが「商品名」「金額」「消費税率」を入力可
  • 消費税を計算して、税込み金額を表示
  • 複数の商品をリストに追加し、最終的な合計金額を算出
  • 日本円から他の通貨(USD, EUR など)への換算

作成したアプリのイメージ

アプリ紹介動画

利用技術

  • React
  • TypeScript
  • Vite
  • Tailwind
  • zod
  • react hook form
  • Bitifinex API

意識したポイント

為替レートの取得はBitifinexの公開APIを利用

fetchExchangeRate.ts
export const fetchExchangeRate = async (from: string, to: string) => {
  const url = `/api/v2/calc/fx`;
  const headers = { "Content-Type": "application/json" };
  const body = JSON.stringify({ ccy1: from, ccy2: to });

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: headers,
      body: body,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data[0];
  } catch (error) {
    console.error("Fetching error:", error);
    throw error;
  }
};

今回は税抜、税込金額だけでなく、為替レートを取得する外部APIを利用し、
アメリカドルとユーロを金額計算時に変換できるように実装しました。
Bitifinex API

CORS問題をプロキシで解決

vite.config.ts
export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: "https://api.bitfinex.com",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
});

当初、データフェッチ時にローカルサーバとBitfinexのオリジンが異なるため、
CORSポリシーでブロックされてしまいました。
そのため、プロキシサーバを介してフェッチするようにしました。
Viteでは、コンフィグに設定を追加し、npm runで実行するだけで
プロキシを簡単に設定できるため、非常に便利だと感じました。

Github

GitHubにコードをアップロードしていますので、よかったら確認してみてください。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?