react-easy-api
v1.0.1
Published
React hooks for easy Axios API integration with TypeScript support
Maintainers
Readme
Easy Axios
React hooks for easy Axios API integration with TypeScript support.
설치
npm install easy-axios
# or
yarn add easy-axios필수 의존성
이 라이브러리는 다음 패키지들이 필요합니다:
npm install react axios기본 사용법
1. Axios 인스턴스 설정
import axios from "axios";
const apiClient = axios.create({
baseURL: "https://api.example.com",
timeout: 10000,
});2. useApi 훅 사용
import { useApi } from "easy-axios";
interface User {
id: number;
name: string;
email: string;
}
function UserProfile({ userId }: { userId: number }) {
const { loading, error, data, execute } = useApi<User>({
endpoint: `/users/${userId}`,
method: "GET",
axiosInstance: apiClient,
enableLogging: true,
});
React.useEffect(() => {
execute();
}, [execute]);
if (loading) return <div>로딩 중...</div>;
if (error) return <div>에러: {error.message}</div>;
if (!data) return <div>데이터가 없습니다.</div>;
return (
<div>
<h1>{data.name}</h1>
<p>{data.email}</p>
</div>
);
}3. POST 요청 사용
interface CreateUserPayload {
name: string;
email: string;
}
function CreateUser() {
const { loading, error, execute } = useApi<User, CreateUserPayload>({
endpoint: "/users",
method: "POST",
axiosInstance: apiClient,
onSuccess: (user) => {
console.log("사용자 생성 성공:", user);
},
onError: (error) => {
console.error("사용자 생성 실패:", error);
},
});
const handleSubmit = async (formData: CreateUserPayload) => {
await execute(formData);
};
return (
<form
onSubmit={(e) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
handleSubmit({
name: formData.get("name") as string,
email: formData.get("email") as string,
});
}}
>
<input name="name" placeholder="이름" required />
<input name="email" type="email" placeholder="이메일" required />
<button type="submit" disabled={loading}>
{loading ? "생성 중..." : "사용자 생성"}
</button>
{error && <p>에러: {error.message}</p>}
</form>
);
}고급 기능
응답 포매터 사용
import { useApi, responseFormatters } from "easy-axios";
interface ApiResponse<T> {
data: T;
message: string;
success: boolean;
}
const { data, execute } = useApi<ApiResponse<User[]>, void, User[]>({
endpoint: "/users",
axiosInstance: apiClient,
responseFormatter: responseFormatters.standard,
});createApiHook으로 재사용 가능한 훅 생성
import { createApiHook } from "easy-axios";
const useUserApi = createApiHook<User>({
method: "GET",
axiosInstance: apiClient,
enableLogging: true,
});
// 사용
const userHook = useUserApi("/users/1");API 참조
useApi Options
| 옵션 | 타입 | 필수 | 설명 |
| ------------------- | ------------------------------------------------- | ---- | --------------------------- |
| endpoint | string | ✓ | API 엔드포인트 |
| method | "GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE" | | HTTP 메서드 (기본값: "GET") |
| axiosInstance | AxiosInstance | ✓ | Axios 인스턴스 |
| responseFormatter | (data: T) => R | | 응답 데이터 변환 함수 |
| onSuccess | (data: R) => void | | 성공 콜백 |
| onError | (error: ApiError) => void | | 에러 콜백 |
| enableLogging | boolean | | 콘솔 로그 활성화 |
useApi Return
| 속성 | 타입 | 설명 |
| --------- | ------------------------------------------- | ------------------ |
| loading | boolean | 로딩 상태 |
| error | ApiError \| null | 에러 정보 |
| data | T \| null | 응답 데이터 |
| execute | (payload?, config?) => Promise<T \| null> | API 요청 실행 함수 |
| reset | () => void | 상태 초기화 함수 |
라이센스
KimByeongNyeon
