260123_ENH : Layout가지 완성된 최초 commit
This commit is contained in:
56
src/hooks/useLoading.ts
Normal file
56
src/hooks/useLoading.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
"use client";
|
||||
|
||||
import { useAtom } from "jotai";
|
||||
import { useCallback } from "react";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export const useLoading = () => {
|
||||
const [isLoading, setIsLoading] = useAtom(loadingAtom);
|
||||
|
||||
const showLoading = useCallback(() => {
|
||||
setIsLoading(true);
|
||||
}, [setIsLoading]);
|
||||
|
||||
const hideLoading = useCallback(() => {
|
||||
setIsLoading(false);
|
||||
}, [setIsLoading]);
|
||||
|
||||
/**
|
||||
* 비동기 함수 호출 시 편하게 쓸 수 있는 래퍼
|
||||
*
|
||||
* 예)
|
||||
* const { withLoading } = useLoading();
|
||||
* await withLoading(() => apiCall());
|
||||
*/
|
||||
const withLoadingAsync = useCallback(
|
||||
async <T,>(fn: () => Promise<T>): Promise<T> => {
|
||||
showLoading();
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
hideLoading();
|
||||
}
|
||||
},
|
||||
[showLoading, hideLoading],
|
||||
);
|
||||
|
||||
const withLoading = useCallback(
|
||||
<T,>(fn: () => T): T => {
|
||||
showLoading();
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
hideLoading();
|
||||
}
|
||||
},
|
||||
[showLoading, hideLoading],
|
||||
);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
showLoading,
|
||||
hideLoading,
|
||||
withLoading,
|
||||
withLoadingAsync,
|
||||
} as const;
|
||||
}
|
||||
Reference in New Issue
Block a user