Skip to content
adynato-mobile-api logo

Mobile API Skill

adynato-mobile-api

API integration patterns for Adynato mobile apps. Covers data fetching with TanStack Query, authentication flows, offline support, error handling, and optimistic updates in React Native/Expo apps. Use when integrating APIs into mobile applications.

SKILL.md

Full skill instructions

Mobile API Skill

Use this skill when integrating APIs into Adynato mobile apps.

Stack

  • Data Fetching: TanStack Query (React Query)
  • HTTP Client: Fetch API or Axios
  • Auth Storage: expo-secure-store
  • Offline: TanStack Query persistence

Setup

Query Client Configuration

// lib/​query-client.ts
import { QueryClient } from '@tanstack/​react-query'

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
      gcTime: 1000 * 60 * 30,   // 30 minutes (formerly cacheTime)
      retry: 2,
      refetchOnWindowFocus: false, // Mobile doesn't have window focus
    },
    mutations: {
      retry: 1,
    },
  },
})

Provider Setup

// app/​_layout.tsx
import { QueryClientProvider } from '@tanstack/​react-query'
import { queryClient } from '@/​lib/​query-client'

export default function RootLayout() {
  return (
    <QueryClientProvider client={queryClient}>
      <Stack />
    </​QueryClientProvider>
  )
}

API Client

Base Configuration

// lib/​api.ts
import * as SecureStore from 'expo-secure-store'

const API_URL = process.env.EXPO_PUBLIC_API_URL

interface RequestOptions extends RequestInit {
  requireAuth?: boolean
}

export async function api<T>(
  endpoint: string,
  options: RequestOptions = {}
): Promise<T> {
  const { requireAuth = true, ...fetchOptions } = options

  const headers: HeadersInit = {
    'Content-Type': 'application/​json',
    ...fetchOptions.headers,
  }

  if (requireAuth) {
    const token = await SecureStore.getItemAsync('auth_token')
    if (token) {
      headers['Authorization'] = `Bearer ${token}`
    }
  }

  const response = await fetch(`${API_URL}${endpoint}`, {
    ...fetchOptions,
    headers,
  })

  if (!response.ok) {
    const error = await response.json().catch(() => ({}))
    throw new ApiError(response.status, error.error || 'Request failed')
  }

  // Handle 204 No Content
  if (response.status === 204) {
    return undefined as T
  }

  return response.json()
}

export class ApiError extends Error {
  constructor(public status: number, message: string) {
    super(message)
    this.name = 'ApiError'
  }
}

API Functions

// lib/​api/​users.ts
import { api } from '@/​lib/​api'

export interface User {
  id: string
  email: string
  name: string
}

export const usersApi = {
  getMe: () => api<{ data: User }>('/​api/​users/​me'),

  getById: (id: string) => api<{ data: User }>(`/​api/​users/​${id}`),

  update: (id: string, data: Partial<User>) =>
    api<{ data: User }>(`/​api/​users/​${id}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
}

Query Hooks

Basic Query

// hooks/​useUser.ts
import { useQuery } from '@tanstack/​react-query'
import { usersApi } from '@/​lib/​api/​users'

export function useUser(id: string) {
  return useQuery({
    queryKey: ['users', id],
    queryFn: () => usersApi.getById(id),
    enabled: !!id,
  })
}

Query with Transform

export function useCurrentUser() {
  return useQuery({
    queryKey: ['users', 'me'],
    queryFn: usersApi.getMe,
    select: (response) => response.data, // Extract data from wrapper
  })
}

Paginated Query

import { useInfiniteQuery } from '@tanstack/​react-query'

export function useUsersList() {
  return useInfiniteQuery({
    queryKey: ['users', 'list'],
    queryFn: ({ pageParam = 1 }) =>
      api(`/​api/​users?page=${pageParam}&limit=20`),
    getNextPageParam: (lastPage, pages) => {
      if (lastPage.data.length < 20) return undefined
      return pages.length + 1
    },
    initialPageParam: 1,
  })
}

Mutations

Basic Mutation

// hooks/​useUpdateProfile.ts
import { useMutation, useQueryClient } from '@tanstack/​react-query'
import { usersApi } from '@/​lib/​api/​users'

export function useUpdateProfile() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<User> }) =>
      usersApi.update(id, data),

    onSuccess: (response, { id }) => {
      // Update cache
      queryClient.setQueryData(['users', id], response)
      queryClient.invalidateQueries({ queryKey: ['users', 'me'] })
    },
  })
}

Optimistic Update

export function useToggleFavorite() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (itemId: string) => api(`/​api/​favorites/​${itemId}`, {
      method: 'POST'
    }),

    onMutate: async (itemId) => {
      // Cancel outgoing refetches
      await queryClient.cancelQueries({ queryKey: ['items', itemId] })

      // Snapshot previous value
      const previousItem = queryClient.getQueryData(['items', itemId])

      // Optimistically update
      queryClient.setQueryData(['items', itemId], (old: any) => ({
        ...old,
        isFavorite: !old.isFavorite,
      }))

      return { previousItem }
    },

    onError: (err, itemId, context) => {
      // Rollback on error
      queryClient.setQueryData(['items', itemId], context?.previousItem)
    },

    onSettled: (data, error, itemId) => {
      // Refetch to ensure sync
      queryClient.invalidateQueries({ queryKey: ['items', itemId] })
    },
  })
}

Authentication Flow

Login

// hooks/​useAuth.ts
import { useMutation, useQueryClient } from '@tanstack/​react-query'
import * as SecureStore from 'expo-secure-store'
import { router } from 'expo-router'
import { api } from '@/​lib/​api'

interface LoginInput {
  email: string
  password: string
}

export function useLogin() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (input: LoginInput) =>
      api<{ token: string; user: User }>('/​api/​auth/​login', {
        method: 'POST',
        body: JSON.stringify(input),
        requireAuth: false,
      }),

    onSuccess: async (response) => {
      await SecureStore.setItemAsync('auth_token', response.token)
      queryClient.setQueryData(['users', 'me'], { data: response.user })
      router.replace('/(tabs)')
    },
  })
}

export function useLogout() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async () => {
      await SecureStore.deleteItemAsync('auth_token')
    },

    onSuccess: () => {
      queryClient.clear()
      router.replace('/(auth)/​login')
    },
  })
}

Auth State Check

// hooks/​useAuthState.ts
import { useQuery } from '@tanstack/​react-query'
import * as SecureStore from 'expo-secure-store'

export function useAuthState() {
  return useQuery({
    queryKey: ['auth', 'state'],
    queryFn: async () => {
      const token = await SecureStore.getItemAsync('auth_token')
      return { isAuthenticated: !!token }
    },
    staleTime: Infinity,
  })
}

Error Handling

Global Error Handler

// In query client setup
const queryClient = new QueryClient({
  defaultOptions: {
    mutations: {
      onError: (error) => {
        if (error instanceof ApiError) {
          if (error.status === 401) {
            // Handle unauthorized - redirect to login
            SecureStore.deleteItemAsync('auth_token')
            router.replace('/(auth)/​login')
            return
          }
        }
        // Show toast or alert
        Alert.alert('Error', error.message)
      },
    },
  },
})

Per-Query Error Handling

function ProfileScreen() {
  const { data, error, isLoading, refetch } = useCurrentUser()

  if (isLoading) return <LoadingSpinner />

  if (error) {
    return (
      <ErrorView
        message={error.message}
        onRetry={refetch}
      />
    )
  }

  return <ProfileContent user={data} />
}

Offline Support

Query Persistence

// lib/​query-client.ts
import { createAsyncStoragePersister } from '@tanstack/​query-async-storage-persister'
import AsyncStorage from '@react-native-async-storage/​async-storage'
import { persistQueryClient } from '@tanstack/​react-query-persist-client'

const asyncStoragePersister = createAsyncStoragePersister({
  storage: AsyncStorage,
})

persistQueryClient({
  queryClient,
  persister: asyncStoragePersister,
})

Network Status

// hooks/​useNetworkStatus.ts
import { useEffect, useState } from 'react'
import NetInfo from '@react-native-community/​netinfo'
import { onlineManager } from '@tanstack/​react-query'

export function useNetworkStatus() {
  const [isOnline, setIsOnline] = useState(true)

  useEffect(() => {
    return NetInfo.addEventListener((state) => {
      const online = !!state.isConnected
      setIsOnline(online)
      onlineManager.setOnline(online)
    })
  }, [])

  return isOnline
}

Usage in Components

// screens/​ProfileScreen.tsx
import { useCurrentUser, useUpdateProfile } from '@/​hooks/​useUser'

export function ProfileScreen() {
  const { data: user, isLoading } = useCurrentUser()
  const updateProfile = useUpdateProfile()

  const handleSave = (formData: Partial<User>) => {
    updateProfile.mutate(
      { id: user.id, data: formData },
      {
        onSuccess: () => {
          Alert.alert('Success', 'Profile updated!')
        },
      }
    )
  }

  if (isLoading) return <LoadingSpinner />

  return (
    <ProfileForm
      user={user}
      onSave={handleSave}
      isSaving={updateProfile.isPending}
    />
  )
}

Checklist

Before shipping:

  • Auth token stored in SecureStore (not AsyncStorage)
  • 401 responses trigger logout/​re-auth
  • Loading states shown during fetches
  • Error states with retry options
  • Optimistic updates where appropriate
  • Offline support if required
  • Request timeouts configured
  • No sensitive data logged

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View