1.0.1 • Published 27 days ago
@wisdomstar94/react-api v1.0.1
react-api
본 레포지토리는 비동기 처리(api 연동 등)와 관련한 여러 상태들을 제공하는 리액트 훅 레포지토리 입니다. api 로부터 아직 응답을 받기 전까지는 추가 요청을 막아야 하는 처리를 일일이 해주는 게 불편하기도 해서 TanStack Query(React-Query) 구조에 영감을 받아 제작해보았습니다.
example code
"use client"
import { useApi } from "@wisdomstar94/react-api";
import axios from "axios";
import { useEffect } from "react";
import styles from './page.module.scss';
interface Item {
status: {
verified: boolean;
sentCount: number;
};
_id: string;
user: string;
text: string;
__v: number;
source: string;
updatedAt: string;
type: string;
createdAt: string;
deleted: boolean;
used: boolean;
}
export default function Page() {
const api = useApi({
api: () => {
const cancelTokenSource = axios.CancelToken.source();
const instance = axios.create({
cancelToken: cancelTokenSource.token,
});
return {
fn: async() => {
const res = await instance({
url: `https://cat-fact.herokuapp.com/facts/`,
method: 'get',
params: {
a: 'b',
},
});
const result: Item[] = res.data;
return result;
},
cancel() {
cancelTokenSource.cancel();
},
};
},
enabledAutoFetch: false,
retryCount: 3,
});
useEffect(() => {
if (api.data === undefined) return;
console.log('@@@@@@@@ api.data', api.data);
}, [api.data]);
useEffect(() => {
if (api.error === undefined) return;
console.log('@@@@@@@@ api.error', api.error);
}, [api.error]);
return (
<>
<div className="w-full relative flex flex-wrap gap-2">
<div className="w-full relative flex flex-wrap gap-2">
<div className="w-full relative flex flex-wrap gap-2">
<button onClick={() => api.fetch()} className="inline-flex px-3 py-1.5 text-xs text-slate-600 border border-slate-400 rounded-lg cursor-pointer hover:bg-slate-100">
api fetch 하기
</button>
</div>
<div className="w-full relative flex flex-wrap gap-2">
<button onClick={() => api.cancel()} className="inline-flex px-3 py-1.5 text-xs text-slate-600 border border-slate-400 rounded-lg cursor-pointer hover:bg-slate-100">
api fetch 취소 하기
</button>
</div>
</div>
<div className="w-full relative flex flex-wrap gap-2">
{ api.isLoading ? '로딩중...' : '' }
</div>
<ul className="w-full relative flex flex-wrap gap-2">
{
api.data?.map(item => {
return (
<li key={item._id} className="w-full flex flex-wrap relative">
<table className={styles['table']}>
<tbody>
<tr>
<th>
status
</th>
<td>
verified: { item.status.verified } <br />
sentCount: { item.status.sentCount }
</td>
</tr>
<tr>
<th>
_id
</th>
<td>
{ item._id }
</td>
</tr>
<tr>
<th>
user
</th>
<td>
{ item.user }
</td>
</tr>
<tr>
<th>
createdAt
</th>
<td>
{ item.createdAt }
</td>
</tr>
</tbody>
</table>
</li>
);
})
}
</ul>
</div>
</>
);
}
보다 더 자세한 예제 코드는 본 레포지토리의 src/app/test/* 경로를 참조해주세요.
test
각 기능들 별로 별도의 테스트 페이지를 만들어 두었습니다. 본 프로젝트를 pull 받아 로컬에서 구동하시고 "http://localhost:3330" 에 접근하시면 각 테스트 페이지로 이동할 수 있는 버튼들이 표시됩니다.