Skip to content

React Example

Demo WebsiteGitHub Source Code

Overview

This example demonstrates how to integrate ApiSorcery with React projects. React is a popular JavaScript library for building user interfaces, and with TypeScript support, it provides an excellent developer experience for modern web applications.

Features

  • Type safety: Full TypeScript support with generated interfaces and types
  • React Hooks: Modern React patterns with hooks for state management
  • Axios integration: Built-in support for Axios HTTP client with interceptors
  • IntelliSense support: Full IDE support with auto-completion and type checking
  • Tree shaking: Optimized bundle size with ES modules support

Quick Setup

1. Install ApiSorcery

bash
npm install -g autoapi

2. Initialize Configuration

bash
autoapi init -l ts

This creates a .autoapirc.json configuration file:

json
{
  "application": {
    "language": "ts",
    "outputDir": "./src/api/auto"
  },
  "services": [
    {
      "code": "demo",
      "token": "72735b33815c4e5c9c2a924a8f4907ef",
      "version": 3,
      "enabled": true,
      "source": "https://your-api.com/swagger.json"
    }
  ]
}

3. Install Dependencies

bash
npm install axios
npm install -D @types/node

4. Generate API Client

bash
autoapi generate

5. Use in React

typescript
import { useState, useEffect } from 'react';
import * as ApiUser from '@/apis/auto/demo/ApiUser';

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchUsers = async () => {
      setLoading(true);
      try {
        const res = await ApiUser.getUserPaged({
          pagination: {
            page: 1,
            limit: 10,
          },
        });
        setUsers(res.results || []);
      } catch (error) {
        console.error('Failed to fetch users:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  return (
    <div>
      {loading ? <p>Loading...</p> : <ul>{users.map(user => <li key={user.id}>{user.name}</li>)}</ul>}
    </div>
  );
}

React Integration Patterns

Custom Hook for API Calls

typescript
import { useState, useEffect } from 'react';
import { ApiMain } from '@/api/auto/main/api';

export function useUsers() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);
  const apiMain = new ApiMain();

  const fetchUsers = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await apiMain.getUsers();
      setUsers(response.data || []);
    } catch (err) {
      setError(err as Error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  return { users, loading, error, refetch: fetchUsers };
}

Using with React Query

typescript
import { useQuery } from '@tanstack/react-query';
import { ApiMain } from '@/api/auto/main/api';

const apiMain = new ApiMain();

export function useUsers() {
  return useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const response = await apiMain.getUsers();
      return response.data || [];
    },
  });
}

// Usage in component
function UserList() {
  const { data: users, isLoading, error } = useUsers();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <ul>
      {users?.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Best Practices

  1. Type Definitions: Leverage generated TypeScript interfaces for better type safety
  2. Error Handling: Implement proper error boundaries and error handling strategies
  3. Request Interceptors: Use Axios interceptors for authentication and request/response transformation
  4. Environment Configuration: Use different API endpoints for development, staging, and production
  5. Code Splitting: Implement lazy loading for API modules to optimize bundle size
  6. Custom Hooks: Create reusable custom hooks for common API operations
  7. State Management: Consider using React Query or SWR for advanced caching and synchronization