SuperAPI AI Directory

ssd-react-api

Coding & development

View repository

Updated 10-15 21:36

About this skill

SSD React API — Standard for calling APIs with Axios and React Query

Context

SSD uses Axios for HTTP requests and TanStack React Query for server state management. All API-related files must be stored in src/app/api/ with 2 ways to create an API client: use NSwag (recommended) or write it yourself

Main rules

  1. All API client files must be stored in src/app/api/
  2. You should use NSwag to generate the Axios API client first
  3. React Query hook files are named after the Controller and end with .query.ts
  4. You must declare queryKeys as an object for every query file
  5. You must always handle error responses from the API (isSuccess check)

API file structure

src/app/api/
├── orderApi.client.ts   # สร้างจาก NSwag (ชื่อลงท้าย .client.ts)
├── orderApi.ts          # เขียนเองกรณี NSwag ไม่พอ
├── order.query.ts       # React Query hooks
│
└── sale/               # กรณีต่อหลาย API ให้สร้าง folder
    ├── saleApi.client.ts
    └── slip.query.ts

Method 1: Use NSwag to generate the API Client (recommended)

Step 1: Set API_URL in .env

API_URL=https://localhost:5001
# NSwag จะดึง swagger จาก https://localhost:5001/swagger/v1/swagger.json

Step 2: Run code generation

npm run code-gen

Step 3: Rename the file

The program will generate the file api.ts in src/api/ Rename it according to the Standard, e.g. orderApi.client.ts

Method 2: Write the Axios API Client yourself

Use when NSwag cannot accommodate:

import axios, { AxiosResponse } from "axios";
import { API_URL } from "../../Const";

// ต้องประกาศ Interface ของ Response
export interface OrderResponseDtoListServiceResponse {
    data?: OrderResponseDto[] | undefined;
    isSuccess?: boolean;
    message?: string | undefined;
    code?: number | undefined;
    exceptionMessage?: any | undefined;
    totalAmountRecords?: number | undefined;
    currentPage?: number | undefined;
    recordsPerPage?: number | undefined;
}

// GET — ดึงรายการ
export const getOrderGetAll = (
    page?: number,
    recordsPerPage?: number,
    sortColumn?: string,
    ordering?: string
): Promise<OrderResponseDto[]> => {
    return axios
        .get(`${API_URL}/order`, {
            params: { page, recordsPerPage, sortColumn, ordering },
        })
        .catch((_error: any) => {
            if (_error.response) return _error.response;
            else throw _error;
        })
        .then((response: AxiosResponse<OrderResponseDtoListServiceResponse>) => {
            if (!response.data.isSuccess)
                throw new Error(response.data.exceptionMessage);
            return response.data.data;
        });
};

// GET — ดึงรายการเดียว
export const getOrderGetById = (id: number): Promise<OrderResponseDto> => {
    return axios
        .get(`${API_URL}/order/${id}`)
        .catch((_error: any) => {
            if (_error.response) return _error.response;
            else throw _error;
        })
        .then((response: AxiosResponse<OrderResponseDtoServiceResponse>) => {
            if (!response.data.isSuccess)
                throw new Error(response.data.exceptionMessage);
            return response.data;
        });
};

// POST — สร้างข้อมูลใหม่
export const postOrderCreate = (
    orderRequestDto: OrderRequestDto
): Promise<OrderResponseDto> => {
    return axios
        .post(`${API_URL}/order`, orderRequestDto)
        .catch((_error: any) => {
            if (_error.response) return _error.response;
            else throw _error;
        })
        .then((response: AxiosResponse<OrderResponseDtoServiceResponse>) => {
            if (!response.data.isSuccess)
                throw new Error(response.data.exceptionMessage);
            return response.data.data;
        });
};

// PUT — อัพเดทข้อมูล
export const putOrderUpdate = (
    id: number,
    orderRequestDto: OrderRequestDto
): Promise<OrderResponseDto> => {
    return axios
        .put(`${API_URL}/order/${id}`, orderRequestDto)
        .catch((_error: any) => {
            if (_error.response) return _error.response;
            else throw _error;
        })
        .then((response: AxiosResponse<OrderResponseDtoServiceResponse>) => {
            if (!response.data.isSuccess)
                throw new Error(response.data.exceptionMessage);
            return response.data;
        });
};

Writing React Query Hooks

File name: [controllerName].query.ts e.g. order.query.ts

// order.query.ts
import { useQuery, useMutation } from "react-query";
import { API_URL } from "../../Const";

// ต้องประกาศ queryKeys เป็น object
export const queryKeys = {
    orderGetAll: "orderGetAll",
    orderGetById: "orderGetById",
};

// Interface สำหรับ request parameters
export interface OrderGetAllRequest {
    page?: number;
    sortBy?: string;
    sortOrder?: string;
    recordsPerPage?: number;
}

// useQuery — ดึงข้อมูล
export const useOrderGetAll = (
    request: OrderGetAllRequest,
    onSuccessCallback?: (data: OrderListResponse) => void,
    onErrorCallback?: (error: Error) => void
) => {
    return useQuery<OrderListResponse, Error>(
        [queryKeys.orderGetAll, request], // query key + dependency
        () => orderClient.getAll(
            request.page,
            request.sortBy,
            request.sortOrder,
            request.recordsPerPage
        ),
        {
            staleTime: 1000 * 60 * 5,       // ข้อมูล stale หลัง 5 นาที
            cacheTime: 1000 * 60 * 10,      // cache ไว้ 10 นาที
            refetchOnWindowFocus: true,      // refetch เมื่อ focus หน้าต่าง
            onSuccess: (data) => {
                if (!data.isSuccess)
                    onErrorCallback?.(new Error(data.message || "Unknown error"));
                onSuccessCallback?.(data);
            },
            onError: (error) => {
                onErrorCallback?.(error);
            },
        }
    );
};

// useQuery — ดึงรายการเดียว
export const useOrderGetById = (
    id: number,
    onSuccessCallback?: (data: OrderResponse) => void,
    onErrorCallback?: (error: Error) => void
) => {
    return useQuery<OrderResponse, Error>(
        [queryKeys.orderGetById, id],
        () => orderClient.getById(id),
        {
            onSuccess: (data) => {
                if (!data.isSuccess)
                    onErrorCallback?.(new Error(data.message || "Unknown error"));
                onSuccessCallback?.(data);
            },
            onError: (error) => onErrorCallback?.(error),
        }
    );
};

// useMutation — สร้างหรืออัพเดทข้อมูล
export const useOrderCreate = (
    onSuccessCallback?: (data: OrderResponse) => void,
    onErrorCallback?: (error: Error) => void
) => {
    return useMutation<OrderResponse, Error, OrderRequestDto>(
        (request) => orderClient.create(request),
        {
            onSuccess: (data) => {
                if (!data?.isSuccess)
                    onErrorCallback?.(new Error(data?.message || "Unknown error"));
                onSuccessCallback?.(data);
            },
            onError: (error) => onErrorCallback?.(error),
        }
    );
};

export const useOrderUpdate = (
    id: number,
    onSuccessCallback?: (data: OrderResponse) => void,
    onErrorCallback?: (error: Error) => void
) => {
    return useMutation<OrderResponse, Error, OrderRequestDto>(
        (request) => orderClient.update(id, request),
        {
            onSuccess: (data) => {
                if (!data?.isSuccess)
                    onErrorCallback?.(new Error(data?.message || "Unknown error"));
                onSuccessCallback?.(data);
            },
            onError: (error) => onErrorCallback?.(error),
        }
    );
};

Main concepts of React Query

  • Fetching + Caching — fetch data and cache it, reducing repeated API calls
  • Automatic Refetching — automatically refetch when the window is focused or data is stale
  • Background Syncing — update state without waiting for the user
  • Mutation — handle create/update/delete with loading/error state