Skills Agentes

Expo Data Fetching

Framework (OSS). Úsalo para cualquier petición de red, llamada a API o data fetching: fetch, React Query, SWR, manejo de errores, caché, soporte offline y loaders de Expo Router (useLoaderData).

Oficial

Reemplaza a: axios

Estrellas
2.6k

en todo el repo

Actividad
58

0–100, la ruta de este skill

Actualizado
hace 3 meses

último commit aquí

Commits
3

últimos 90 días

Contexto
2.8k tok

57 tok en reposo

Paquete
4 archivos

22 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add expo/skills --skill expo-data-fetching --agent claude-code

Se instala solo en este repositorio.

Este skill makes network requests, reads environment config.

Qué hace

  • Implementa fetch, React Query/SWR, manejo de errores, autenticación con expo-secure-store y variables EXPO_PUBLIC_
  • Cubre offline con NetInfo, cancelación con AbortController y loaders de Expo Router (useLoaderData, web SDK 55+)

Úsalo cuando

  • Al implementar peticiones API o configurar data fetching (React Query, SWR)
  • Al depurar fallos de red o implementar estrategias de caché
  • Al gestionar autenticación/tokens o configurar URLs de API y variables de entorno
  • Al usar loaders de datos de Expo Router (useLoaderData, web SDK 55+)

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • “¿Cómo hago llamadas a la API en React Native?”
    • “¿Debería usar React Query o SWR?”
    • “Mi app necesita funcionar offline”
    • “¿Cómo manejo los tokens de autenticación?”
    • “¿Cómo configuro distintas URLs de API para dev y prod?”

    SKILL.md

    En inglés

    Expo Networking

    You MUST use this skill for ANY networking work including API requests, data fetching, caching, or network debugging.

    References

    Consult these resources as needed:

    references/
      expo-router-loaders.md        Route-level data loading with Expo Router loaders (web, SDK 55+)
      offline-and-cancellation.md   NetInfo network status, offline-first React Query, AbortController
    

    When to Use

    Use this skill when:

    • Implementing API requests
    • Setting up data fetching (React Query, SWR)
    • Using Expo Router data loaders (useLoaderData, web SDK 55+)
    • Debugging network failures
    • Implementing caching strategies
    • Handling offline scenarios
    • Authentication/token management
    • Configuring API URLs and environment variables

    Preferences

    • Avoid axios, prefer expo/fetch

    Common Issues & Solutions

    1. Basic Fetch Usage

    Simple GET request:

    const fetchUser = async (userId: string) => {
      const response = await fetch(`https://api.example.com/users/${userId}`);
    
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    
      return response.json();
    };
    

    POST request with body:

    const createUser = async (userData: UserData) => {
      const response = await fetch("https://api.example.com/users", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(userData),
      });
    
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message);
      }
    
      return response.json();
    };
    

    2. React Query (TanStack Query)

    Setup:

    // app/_layout.tsx
    import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
    
    const queryClient = new QueryClient({
      defaultOptions: {
        queries: {
          staleTime: 1000 * 60 * 5, // 5 minutes
          retry: 2,
        },
      },
    });
    
    export default function RootLayout() {
      return (
        <QueryClientProvider client={queryClient}>
          <Stack />
        </QueryClientProvider>
      );
    }
    

    Fetching data:

    import { useQuery } from "@tanstack/react-query";
    
    function UserProfile({ userId }: { userId: string }) {
      const { data, isLoading, error, refetch } = useQuery({
        queryKey: ["user", userId],
        queryFn: () => fetchUser(userId),
      });
    
      if (isLoading) return <Loading />;
      if (error) return <Error message={error.message} />;
    
      return <Profile user={data} />;
    }
    

    Mutations:

    import { useMutation, useQueryClient } from "@tanstack/react-query";
    
    function CreateUserForm() {
      const queryClient = useQueryClient();
    
      const mutation = useMutation({
        mutationFn: createUser,
        onSuccess: () => {
          // Invalidate and refetch
          queryClient.invalidateQueries({ queryKey: ["users"] });
        },
      });
    
      const handleSubmit = (data: UserData) => {
        mutation.mutate(data);
      };
    
      return <Form onSubmit={handleSubmit} isLoading={mutation.isPending} />;
    }
    

    3. Error Handling

    Comprehensive error handling:

    class ApiError extends Error {
      constructor(message: string, public status: number, public code?: string) {
        super(message);
        this.name = "ApiError";
      }
    }
    
    const fetchWithErrorHandling = async (url: string, options?: RequestInit) => {
      try {
        const response = await fetch(url, options);
    
        if (!response.ok) {
          const error = await response.json().catch(() => ({}));
          throw new ApiError(
            error.message || "Request failed",
            response.status,
            error.code
          );
        }
    
        return response.json();
      } catch (error) {
        if (error instanceof ApiError) {
          throw error;
        }
        // Network error (no internet, timeout, etc.)
        throw new ApiError("Network error", 0, "NETWORK_ERROR");
      }
    };
    

    Retry logic:

    const fetchWithRetry = async (
      url: string,
      options?: RequestInit,
      retries = 3
    ) => {
      for (let i = 0; i < retries; i++) {
        try {
          return await fetchWithErrorHandling(url, options);
        } catch (error) {
          if (i === retries - 1) throw error;
          // Exponential backoff
          await new Promise((r) => setTimeout(r, Math.pow(2, i) * 1000));
        }
      }
    };
    

    4. Authentication

    Token management:

    import * as SecureStore from "expo-secure-store";
    
    const TOKEN_KEY = "auth_token";
    
    export const auth = {
      getToken: () => SecureStore.getItemAsync(TOKEN_KEY),
      setToken: (token: string) => SecureStore.setItemAsync(TOKEN_KEY, token),
      removeToken: () => SecureStore.deleteItemAsync(TOKEN_KEY),
    };
    
    // Authenticated fetch wrapper
    const authFetch = async (url: string, options: RequestInit = {}) => {
      const token = await auth.getToken();
    
      return fetch(url, {
        ...options,
        headers: {
          ...options.headers,
          Authorization: token ? `Bearer ${token}` : "",
        },
      });
    };
    

    Token refresh:

    let isRefreshing = false;
    let refreshPromise: Promise<string> | null = null;
    
    const getValidToken = async (): Promise<string> => {
      const token = await auth.getToken();
    
      if (!token || isTokenExpired(token)) {
        if (!isRefreshing) {
          isRefreshing = true;
          refreshPromise = refreshToken().finally(() => {
            isRefreshing = false;
            refreshPromise = null;
          });
        }
        return refreshPromise!;
      }
    
      return token;
    };
    

    5. Offline Support

    Network-status detection with NetInfo and offline-first React Query setup: see ./references/offline-and-cancellation.md.


    6. Environment Variables

    Using environment variables for API configuration:

    Expo supports environment variables with the EXPO_PUBLIC_ prefix. These are inlined at build time and available in your JavaScript code.

    // .env
    EXPO_PUBLIC_API_URL=https://api.example.com
    EXPO_PUBLIC_API_VERSION=v1
    
    // Usage in code
    const API_URL = process.env.EXPO_PUBLIC_API_URL;
    
    const fetchUsers = async () => {
      const response = await fetch(`${API_URL}/users`);
      return response.json();
    };
    

    Environment-specific configuration:

    // .env.development
    EXPO_PUBLIC_API_URL=http://localhost:3000
    
    // .env.production
    EXPO_PUBLIC_API_URL=https://api.production.com
    

    Creating an API client with environment config:

    // api/client.ts
    const BASE_URL = process.env.EXPO_PUBLIC_API_URL;
    
    if (!BASE_URL) {
      throw new Error("EXPO_PUBLIC_API_URL is not defined");
    }
    
    export const apiClient = {
      get: async <T,>(path: string): Promise<T> => {
        const response = await fetch(`${BASE_URL}${path}`);
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        return response.json();
      },
    
      post: async <T,>(path: string, body: unknown): Promise<T> => {
        const response = await fetch(`${BASE_URL}${path}`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
        });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        return response.json();
      },
    };
    

    Important notes:

    • Only variables prefixed with EXPO_PUBLIC_ are exposed to the client bundle
    • Never put secrets (API keys with write access, database passwords) in EXPO_PUBLIC_ variables—they're visible in the built app
    • Environment variables are inlined at build time, not runtime
    • Restart the dev server after changing .env files
    • For server-side secrets in API routes, use variables without the EXPO_PUBLIC_ prefix

    TypeScript support:

    // types/env.d.ts
    declare global {
      namespace NodeJS {
        interface ProcessEnv {
          EXPO_PUBLIC_API_URL: string;
          EXPO_PUBLIC_API_VERSION?: string;
        }
      }
    }
    
    export {};
    

    7. Request Cancellation

    AbortController on unmount (React Query cancels automatically): see ./references/offline-and-cancellation.md.


    Decision Tree

    User asks about networking
      |-- Route-level data loading (web, SDK 55+)?
      |   \-- Expo Router loaders — see references/expo-router-loaders.md
      |
      |-- Basic fetch?
      |   \-- Use fetch API with error handling
      |
      |-- Need caching/state management?
      |   |-- Complex app -> React Query (TanStack Query)
      |   \-- Simpler needs -> SWR or custom hooks
      |
      |-- Authentication?
      |   |-- Token storage -> expo-secure-store
      |   \-- Token refresh -> Implement refresh flow
      |
      |-- Error handling?
      |   |-- Network errors -> Check connectivity first
      |   |-- HTTP errors -> Parse response, throw typed errors
      |   \-- Retries -> Exponential backoff
      |
      |-- Offline support?
      |   |-- Check status -> NetInfo
      |   \-- Queue requests -> React Query persistence
      |
      |-- Environment/API config?
      |   |-- Client-side URLs -> EXPO_PUBLIC_ prefix in .env
      |   |-- Server secrets -> Non-prefixed env vars (API routes only)
      |   \-- Multiple environments -> .env.development, .env.production
      |
      \-- Performance?
          |-- Caching -> React Query with staleTime
          |-- Deduplication -> React Query handles this
          \-- Cancellation -> AbortController or React Query
    

    Common Mistakes

    Wrong: No error handling

    const data = await fetch(url).then((r) => r.json());
    

    Right: Check response status

    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const data = await response.json();
    

    Wrong: Storing tokens in AsyncStorage

    await AsyncStorage.setItem("token", token); // Not secure!
    

    Right: Use SecureStore for sensitive data

    await SecureStore.setItemAsync("token", token);
    

    Example Invocations

    User: "How do I make API calls in React Native?" -> Use fetch, wrap with error handling

    User: "Should I use React Query or SWR?" -> React Query for complex apps, SWR for simpler needs

    User: "My app needs to work offline" -> Use NetInfo for status, React Query persistence for caching

    User: "How do I handle authentication tokens?" -> Store in expo-secure-store, implement refresh flow

    User: "API calls are slow" -> Check caching strategy, use React Query staleTime User: "How do I configure different API URLs for dev and prod?" -> Use EXPO_PUBLIC_ env vars with .env.development and .env.production files User: "Where should I put my API key?" -> Client-safe keys: EXPO_PUBLIC_ in .env. Secret keys: non-prefixed env vars in API routes only

    User: "How do I load data for a page in Expo Router?" -> See references/expo-router-loaders.md for route-level loaders (web, SDK 55+). For native, use React Query or fetch.

    Submitting Feedback

    If you encounter errors, misleading or outdated information in this skill, report it so Expo can improve:

    npx --yes submit-expo-feedback@latest --category skills --subject "expo-data-fetching" "<actionable feedback>"
    

    Only submit when you have something specific and actionable to report. Include as much relevant context as possible. If an AI agent repeatedly failed or the user had to take over an Expo task, load the expo-skill-feedback skill and follow its eval-candidate flow instead of reusing the command above.

    Reproducido de expo/skills bajo licencia MIT. Leer esta página en markdown.

    Archivos

    4 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Antes de instalar

    Necesita en el PATH:npx

    Variables de entorno:API_URLBASE_URLEXPO_PUBLIC_API_URL

    Detalles

    Creador
    expo
    Licencia
    MIT
    Recursos incluidos
    referencias
    Repositorio
    expo/skills
    Código fuente
    Ver SKILL.md

    Más de expo/skills

    Este repo incluye 27 skills. Si instalas uno, normalmente ya tienes los demás. Ver el pack skills entero y su comando de instalación

    Servicio de pago de EAS para ejecutar y controlar la app de un usuario en un simulador remoto de iOS/Android alojado en la nube de EAS, incluso desde agentes de IA.

    Costo de contexto al activarse
    5.7k tok
    Tamaño del paquete
    5 archivos
    Última actualización
    hace 2 meses
    Oficialherramientas desarrollo

    Framework (OSS). Pautas para actualizar versiones del SDK de Expo y resolver problemas de dependencias.

    Costo de contexto al activarse
    1.9k tok
    Tamaño del paquete
    9 archivos
    Última actualización
    hace 2 meses
    Oficialherramientas desarrollo

    Repositorio oficial expo/examples con ~70 integraciones `with-*` (Stripe, Clerk, Supabase, OpenAI, mapas, Reanimated, SQLite, Skia, NativeWind, etc.) para adaptar o scaffoldear proyectos.

    Costo de contexto al activarse
    1.7k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialherramientas desarrollo

    Framework (OSS) para construir UI nativa con el paquete @expo/ui: SwiftUI real en iOS y Jetpack Compose en Android, en vez de Reanimated o librerías de UI de la comunidad RN.

    Costo de contexto al activarse
    1.7k tok
    Tamaño del paquete
    7 archivos
    Última actualización
    hace 2 meses
    Oficialdesarrollo apis

    Framework (OSS). Migra una app web React existente a una app nativa iOS/Android con Expo, screen por screen, usando expo-dom para el mecanismo de shell.

    Costo de contexto al activarse
    2.6k tok
    Tamaño del paquete
    6 archivos
    Última actualización
    hace 2 meses
    Oficialdesarrollo apis

    Framework (OSS). Punto de entrada y enrutador para toda tarea de Expo o EAS: detecta el objetivo real, dirige a la skill expo-* / eas-* correcta y aplica las reglas de configuración compartidas.

    Costo de contexto al activarse
    2.2k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    Oficialherramientas desarrollo

    Skills relacionados

    Referencia para la API de Claude / SDK de Anthropic — IDs de modelo, precios, parámetros, streaming, tool use, MCP, agentes, caching, conteo de tokens y migración de modelos.

    Costo de contexto al activarse
    21.4k tok
    Tamaño del paquete
    70 archivos
    Última actualización
    hace 2 meses
    Oficialdesarrollo apis

    Guía para crear servidores MCP de calidad que permitan a los LLMs interactuar con servicios externos. Úsalo al construir servidores MCP en Python (FastMCP) o Node/TypeScript (MCP SDK).

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    hace 6 meses
    Oficialdesarrollo apis

    Guía completa para integrar servidores Model Context Protocol en plugins de Claude Code, para conectar herramientas y servicios externos.

    Costo de contexto al activarse
    3.1k tok
    Tamaño del paquete
    7 archivos
    Última actualización
    hace 11 meses
    Oficialdesarrollo apis