Community程式設計與開發github.com

expo/native-data-fetching

在實作或除錯任何網路請求、API 呼叫或資料擷取時使用。涵蓋 fetch API、React Query、SWR、錯誤處理、快取、離線支援以及 Expo Router 資料載入器(`useLoaderData`)。

native-data-fetching 是什麼?

這項技能專為在使用 Expo 生態系統(如 React Native 和 Expo Router)進行開發時,處理所有與網路請求相關的任務而設計。它涵蓋了從基本的 fetch API 到進階的資料擷取庫(如 React Query 和 SWR),幫助開發者有效地管理伺服器狀態、處理快取和背景重新整理。此外,它還針對常見的錯誤處理模式、離線支援策略以及 Expo Router 的資料載入器(`useLoaderData`)提供了明確的指引。此技能適用於任何需要除錯網路 API 呼叫或確保應用程式在不同網路狀況下都能穩定運作的場景。無論是實作新的端點還是修復現有的資料載入問題,它都能提供結構化的方法與最佳實踐。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/expo/skills/tree/main/skills/native-data-fetching

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

native-data-fetching 是做什麼的?

在實作或除錯任何網路請求、API 呼叫或資料擷取時使用。涵蓋 fetch API、React Query、SWR、錯誤處理、快取、離線支援以及 Expo Router 資料載入器(useLoaderData)。

概述

此技能提供了一套全面的指南,幫助你在 Expo 與 React Native 專案中實作和除錯資料擷取邏輯。它涵蓋了從原生 fetch 到現代化資料管理解決方案(如 React Query 與 SWR)的各種方法。

核心功能

  • Fetch API: 使用 fetch 進行基本網路請求,包含錯誤處理與自訂標頭。
  • React Query: 使用 @tanstack/react-query 管理伺服器狀態,包括查詢、突變(mutations)、快取與背景重新擷取。
  • SWR: 使用 swr 套件進行資料擷取,結合快取驗證(stale-while-revalidate)策略。
  • 錯誤處理: 統一的錯誤處理機制,包括網路錯誤、HTTP 錯誤狀態碼以及應用程式邏輯錯誤。
  • 快取: 設定記憶體快取、持久化快取(如使用 AsyncStorage)以及自動重新驗證。
  • 離線支援: 實作網路偵測、佇列離線請求,並在恢復連線時同步。
  • Expo Router 載入器: 與 useLoaderData 整合,以在路由層面進行資料擷取與載入狀態管理。

使用方法

// 使用 fetch API 的基本範例
async function fetchUserData(userId: string) {
  try {
    const response = await fetch(`https://api.example.com/users/${userId}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Failed to fetch user data:', error);
    throw error;
  }
}
// 使用 React Query 的範例
import { useQuery } from '@tanstack/react-query';

function useUserData(userId: string) {
  return useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetchUserData(userId),
    staleTime: 5 * 60 * 1000, // 5 分鐘內視為新資料
    cacheTime: 10 * 60 * 1000, // 快取保留 10 分鐘
  });
}
// 使用 Expo Router 資料載入器
import { useLoaderData } from 'expo-router';

export async function loader() {
  const data = await fetchUserData('123');
  return { user: data };
}

export default function UserScreen() {
  const { user } = useLoaderData();
  return <Text>{user.name}</Text>;
}

離線支援

在離線時,你可以使用 @react-native-community/netinfo 監聽網路狀態,並將請求加入佇列,直到連線恢復。

import NetInfo from '@react-native-community/netinfo';

NetInfo.addEventListener(state => {
  console.log('Connection type', state.type);
  console.log('Is connected?', state.isConnected);
});

錯誤處理

始終在 catch 區塊中處理錯誤,並考慮向使用者顯示友善的錯誤訊息。你也可以使用 React Query 的 onError 回呼來處理全域錯誤。

快取策略

  • React Query: 使用 staleTime 控制資料過期時間,cacheTime 控制快取保留時間。
  • SWR: 使用 dedupingInterval 避免重複請求,並搭配 errorRetryCount 設定重試次數。
  • 手動快取: 使用 AsyncStorage 儲存解析後的資料,以加速後續載入。

相關資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

expo/add-app-clip

Add an iOS App Clip target to an Expo app. Use when the user mentions App Clip, AASA, apple-app-site-association, appclips, smart app banner, or wants to ship a lightweight iOS Clip invoked from a URL alongside their parent app.

expo/building-native-ui

Complete guide for building beautiful apps with Expo Router. Covers fundamentals, styling, components, navigation, animations, patterns, and native tabs.

expo/eas-update-insights

Check the health of published EAS Updates: crash rates, install/launch counts, unique users, payload size, and the split between embedded and OTA users per channel. Use when the user asks how an update is performing, whether a rollout is healthy, how many users are on the embedded build vs OTA, or wants to gate CI on update health.

expo/expo-api-routes

Guidelines for creating API routes in Expo Router with EAS Hosting

expo/expo-brownfield

Integrate Expo and React Native into an existing native iOS or Android app. Use when the user mentions brownfield, embedding React Native in a native app, AAR/XCFramework, or adding Expo to an existing Kotlin/Swift project. Covers both the isolated approach and the integrated approach.

expo/expo-cicd-workflows

Helps understand and write EAS workflow YAML files for Expo projects. Use this skill when the user asks about CI/CD or workflows in an Expo or EAS context, mentions .eas/workflows/, or wants help with EAS build pipelines or deployment automation.

expo/expo-deployment

Deploying Expo apps to iOS App Store, Android Play Store, web hosting, and API routes

expo/expo-dev-client

Build and distribute Expo development clients locally or via TestFlight

expo/expo-examples

Framework (OSS). Expo's official example projects - the expo/examples repo of ~70 `with-*` integrations (Stripe, Clerk, Supabase, OpenAI, maps, Reanimated, SQLite, Skia, NativeWind, and more). Use when integrating a third-party library or service into an existing Expo app and you want the canonical, version-matched pattern to adapt, or when scaffolding a new project from one with `npx create-expo --example`.

expo/expo-module

Guide for creating and writing Expo native modules and views using the Expo Modules API (Swift, Kotlin, TypeScript). Covers module definition DSL, native views, shared objects, config plugins, lifecycle hooks, autolinking, and type system. Use when building or modifying native modules for Expo.

expo/expo-observe

Use for anything related to EAS Observe — adding `expo-observe` to an Expo project (AppMetricsRoot/ObserveRoot HOC, markInteractive, the useObserve hook, and the Expo Router / React Navigation integrations for per-route metrics), querying via the EAS CLI (`eas observe:metrics-summary`, `observe:metrics`, `observe:routes`, `observe:events`, `observe:versions`), or interpreting the resulting metrics (cold/warm launch, TTR, TTI, navigation cold/warm TTR, update download, and the TTI frameRate params for triaging slow startups).

expo/expo-overview

Framework (OSS). Entry point and router for every Expo or EAS task. Load this skill first — before writing code and before choosing another expo-* / eas-* skill — when the request, PRD, or spec mentions Expo, EAS, Expo Go, or an expo-* package, or the project has an `expo` dependency in `package.json`. Within that gate it also covers app specs and designs to implement (tabs, stacks, maps, lists, navigation, building from a screenshot), and phrasings like 'implement a mobile app', 'make my app look native', 'add navigation', 'fetch some data', 'upgrade my SDK', 'add Expo to my existing native app', 'ship to the App Store', or 'I'm new to Expo, where do I start'. A fully specified request (SDK pinned, libraries named, layout given) still routes through here — the shared setup rules still apply. Do NOT load it when neither signal is present: a bare React Native project with no `expo` dependency is not Expo work. Detects the real goal, routes to the right expo-* / eas-* skill, and owns the shared setup rules.

expo/expo-router

Framework (OSS). Navigation and routing for Expo Router. Covers file-based routes, groups and dynamic routes, folder organization, Link with previews and context menus, native Stack, page titles, modals and form sheets, NativeTabs, headers and toolbars, and header search bars.

expo/expo-skill-eval

Evaluate Expo skills in this repo end-to-end - trigger accuracy, generated code quality, and runtime screenshots on iOS simulator and Android emulator via Expo Go (web optional). Use when the user wants to eval an Expo skill, test that a skill produces working code, benchmark a skill with device screenshots, or verify a skill's output renders correctly.

expo/expo-tailwind-setup

Set up Tailwind CSS v4 in Expo with react-native-css and NativeWind v5 for universal styling

expo/expo-ui

Framework (OSS). Build native UI with the @expo/ui package: real SwiftUI on iOS and Jetpack Compose on Android. Default to @expo/ui for sheets (BottomSheet), pickers, sliders, toggles, menus, and grouped-form sections — do NOT reach for Reanimated, @gorhom/bottom-sheet, or RN built-in Picker/Switch; use @expo/ui instead. Fall back to RN built-ins only when @expo/ui is missing the component. NOTE: @expo/ui List renders native grouped rows like an iOS Settings screen — it is NOT a virtualized list; use FlatList/FlashList for large datasets. Covers universal components (Host, Column, Row, Button, Text, List, BottomSheet, FieldGroup, Switch, Slider, Picker, Menu), drop-in replacements for RN community libraries, and platform-specific SwiftUI/Jetpack Compose trees. Not for Expo Router navigation, Reanimated, or data fetching.

expo/expo-ui-jetpack-compose

`@expo/ui/jetpack-compose` package lets you use Jetpack Compose Views and modifiers in your app.

expo/expo-ui-swiftui

`@expo/ui/swift-ui` package lets you use SwiftUI Views and modifiers in your app.

expo/expo-upgrade

Framework (OSS). Guidelines for upgrading Expo SDK versions and fixing dependency issues

expo/skills

Build and submit iOS and Android apps with EAS to TestFlight, the App Store, or Google Play. Supports Expo and other React Native projects, plus existing native apps. Use for eas.json setup, release pipelines, signing, app versions and build numbers, store submissions, and listing metadata. For Expo websites and API routes, use eas-hosting; for adding React Native screens to a native app, use expo-brownfield.

相關技能