다음과 같이 반복되는 부분을 hoc를 활용해 줄여보자!
function Parent(){
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);
const [cards, setCards] = useState([]);
const fetcher = async () => {
try{
const response = await fetch(url);
setCards(response.data);
} catch (error) {
setIsError(error);
}
}
useEffect(() => {
fetcher();
},[])
if(isLoading) return <div>Loading</div>
if(isError) return <div>Error</div>
return (
<ul>
cards.map(card => <Child/>)
</ul>
)
}
GET 요청을 하는 로직이 필요한 컴포넌트를 감싸는 컴포넌트, (대부분의 첫화면 렌더링)
useAxios: GET 요청이 로딩 처리, 에러 처리등을 담당
WithLoading: useAxios가 반환한 상태에 따른 컴포넌트 렌더링
적용컴포넌트
EditTeamPost, EditUserProfile, MyList, MyPost, TeamPost, UserPost
export default function TeamPost() {
// 생략
const UserPostDetailWithLoading = WithLoading({
Component: TeamPostDetail, // 데이터 요청 이후 순수한 데이터 렌더링만 담당하는 컴포넌트
responseDataKey: 'targetTeam', // 렌더링을 담당하는 컴포넌트에서 사용할 데이터의 키 값
axiosInstance: teamApi.GET_TEAM_DETAIL,
axiosConfig: { id: teamId },
});
return (
<div>
<button onClick={onClickback}>back</button>
<UserPostDetailWithLoading />
</div>
);
}
무한스크롤을 사용하는 컴포넌트를 감싸는 컴포넌트
WithInfiniteScroll: useIntersect를 사용하는 컴포넌트를 감싸는 컴포넌트