56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
"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;
|
|
} |