1. async 로 Mock Data 제공하는 hook
- input
- resolvedData: 제공할 mock data
- waitingTime : setTimeout 기다리는 시간, 몇 초 후 리턴
- output
- { loading, setLoading, data, setData } : 로딩, 리턴받는 데이터 state
useFakeFetch.ts
- 코드
import { useEffect, useState } from "react";
interface FakeFetchResult<T> {
loading: boolean;
setLoading: React.Dispatch<React.SetStateAction<boolean>>;
data: T[];
setData: React.Dispatch<React.SetStateAction<T[]>>;
}
const useFakeFetch = <T>(resolvedData: T[], waitingTime = 500): FakeFetchResult<T> => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState<T[]>([]);
useEffect(() => {
let isMounted = true;
const timeoutId = setTimeout(() => {
if (isMounted) {
setData(resolvedData);
setLoading(false);
}
}, waitingTime);
return () => {
isMounted = false;
clearTimeout(timeoutId);
};
}, [resolvedData, waitingTime]);
return { loading, setLoading, data, setData };
};
export default useFakeFetch;
MyComponent.tsx
- 사용하는 컴포넌트 코드
const { loading: priceLoading, data: pricing } = useFakeFetch(
pricingData,
1000
);
const { data: newNotifications, setData: setNewNotifications } =
useFakeFetch(rawNewNotifications);
const { data: earlierNotifications, setData: setEarlierNotifications } =
useFakeFetch(rawEarlierNotifications);