Chuyển đến nội dung
Skillpedia
Website và giao diện (frontend)48k · #4661

frontend-api-integration-patterns

Skill này làm gì

Công cụ này giúp kết nối website hoặc ứng dụng của bạn với các dịch vụ trực tuyến khác một cách đáng tin cậy hơn. Nó hướng dẫn cách xử lý các vấn đề thường gặp khi gửi và nhận thông tin, giúp mọi thứ hoạt động trơn tru và không gây lỗi cho người dùng.

Khi nào nên dùng

  • ✓Khi kết nối website của bạn với một dịch vụ dữ liệu.
  • ✓Khi bạn muốn ngăn thông tin cũ xuất hiện trên màn hình.
  • ✓Khi cần sửa lỗi xảy ra lúc tải hoặc gửi dữ liệu.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-api-integration-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm thế nào để website của tôi không hiển thị dữ liệu cũ khi tôi đang lấy thông tin mới?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Công cụ sắp xếp mã giao tiếp với các dịch vụ khác, ngăn gửi các yêu cầu trùng lặp, và đảm bảo rằng nếu kết nối thất bại, nó có thể thử lại một cách thông minh.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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();


…
Câu hỏi thường gặp

'Race condition' là gì?

Đây là khi hai hoặc nhiều thao tác diễn ra cùng lúc, và thứ tự chúng hoàn thành gây ra kết quả không mong muốn hoặc sai.

Vì sao phải hủy yêu cầu?

Để ngăn ứng dụng hiển thị thông tin cũ hoặc bị lỗi, đặc biệt khi người dùng rời trang trước khi nhận được phản hồi.

'Retry strategy' là gì?

Đây là cách thử lại một thao tác khi nó thất bại, với thời gian chờ dài hơn sau mỗi lần thử, để xử lý các sự cố kết nối tạm thời.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#4661
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự