本文へスキップ
Skillpedia
WebサイトとUI(フロントエンド)48k · #4661

frontend-api-integration-patterns

できること

ウェブサイトやアプリを他のオンラインサービスと、より確実に連携させるためのツールです。データの送受信時に起こりやすい問題への対処法を解説し、ユーザーにとってエラーがなく、スムーズに動作するようにします。

使う場面

  • ✓ウェブサイトをデータサービスに接続するとき。
  • ✓画面に古い情報が表示されるのを防ぎたいとき。
  • ✓データの読み込みや送信時に発生するエラーを解決したいとき。

スキルのリンク

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-api-integration-patterns/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-api-integration-patterns/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“データを新しく取得するときに、ウェブサイトに古いデータが表示されないようにするにはどうすればよいですか?”

毎週5つの新しいスキル。1分で読めます。

仕組み

他のサービスと通信するコードを整理し、重複したリクエストが送られないようにします。また、接続に失敗した場合は、賢く再試行できるようにします。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

Frontend API Integration Patterns

Overview

This skill provides production-ready patterns for integrating frontend applications with backend APIs.

Most frontend issues are not caused by APIs being difficult to call, but by incorrect handling of asynchronous behavior—leading to race conditions, stale data, duplicated requests, and poor user experience.

This skill focuses on correctness, resilience, and user experience, not just making API calls work.


When to Use This Skill

  • Connecting frontend apps (React, React Native, Vue, etc.) to backend APIs
  • Integrating ML/AI endpoints (/predict, /recommend)
  • Handling asynchronous data in UI
  • Fixing stale data, flickering UI, or duplicate requests
  • Designing scalable frontend API layers

Core Patterns

1. API Layer (Separation of Concerns)

Centralize API logic and normalize errors.

export class ApiError extends Error {
  constructor(message, status, payload = null) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.payload = payload;
  }
}

export const apiClient = async (url, options = {}) => {
  const res = await fetch(url, {
    headers: { "Content-Type": "application/json" },
    ...options,
  });

  if (!res.ok) {
    let payload = null;
    try {
      payload = await res.json();
    } catch (_) {}

    throw new ApiError(
      payload?.message || "Request failed",
      res.status,
      payload
    );
  }

  // handle empty responses safely (e.g. 204 No Content)
  if (res.status === 204) return null;

  const text = await res.text();
  return text ? JSON.parse(text) : null;
};

2. Race-Safe State Management

Prevent stale responses from overwriting fresh data.

useEffect(() => {
  let cancelled = false;

  const load = async () => {
    try {
      setLoading(true);
      setError(null);

      const result = await getUser();

      if (!cancelled) setData(result);
    } catch (err) {
      if (!cancelled) setError(err.message);
    } finally {
      if (!cancelled) setLoading(false);
    }
  };

  load();

  return () => {
    cancelled = true;
  };
}, []);

Use a cancellation flag for non-fetch async logic. For network requests, prefer AbortController.


3. Request Cancellation (AbortController)

Cancel in-flight requests to avoid memory leaks and stale updates.

useEffect(() => {
  const controller = new AbortController();

  const load = async () => {
    try {
      const data = await getUser({ signal: controller.signal });
      setData(data);
    } catch (err) {
      if (err.name === "AbortError") return;
      setError(err.message);
    }
  };

  load();
  return () => controller.abort();
}, [userId]);

4. Retry with Exponential Backoff

Retry only explicitly replay-safe operations and classified transient failures. The default performs one attempt. Do not classify arbitrary programming or parsing exceptions as network errors. Honor provider Retry-After and a total deadline in the real adapter; do not enable this simple backoff for rate-limit responses. The POST prediction example intentionally does not enable retries unless the backend contract independently guarantees replay safety.

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const fetchWithBackoff = async (fn, retries = 3, delay = 300, replaySafe = false) => {
  try {
    return await fn();
  } catch (err) {
    const isAbort = err.name === "AbortError";
    const isHttpError = typeof err.status === "number";
    const isNetworkFailure = err.code === "NETWORK_ERROR";
    const isRetryable = replaySafe && !isAbort &&
      (isNetworkFailure || (isHttpError && err.status >= 500));

    if (retries <= 0 || !isRetryable) throw err;

    const nextDelay = delay * 2 + Math.random() * 100;
    await sleep(nextDelay);

    return fetchWithBackoff(fn, retries - 1, nextDelay, replaySafe);
  }
};

5. Debounced API Calls

Avoid excessive API calls (e.g., search inputs).

const useDebounce = (value, delay = 400) => {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);

  return debounced;
};

6. Request Deduplication

Prevent duplicate API calls across components.

const inFlight = new Map();


…
よくある質問

「レースコンディション」とは何ですか?

複数の処理が同時に行われ、それらの完了する順番によって、予期しない、または誤った結果になる状態のことです。

なぜリクエストをキャンセルするのですか?

特に、レスポンスが返ってくる前にユーザーが別のページに移動した場合に、アプリケーションが古い情報や壊れた情報を表示しないようにするためです。

「再試行戦略」とは何ですか?

処理が失敗した場合に、もう一度実行する方法のことです。一時的な接続の問題に対応するため、再試行のたびに待ち時間を少しずつ長くします。

詳細

作者による元の説明

Production-ready patterns for integrating frontend applications with backend APIs, including race condition handling, request cancellation, retry strategies, error normalization, and UI state management.

repo: sickn33/agentic-awesome-skills

人気

GitHubのスター
48k
ランキング
#4661
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル