66 lines
1.9 KiB
TypeScript
66 lines
1.9 KiB
TypeScript
/**
|
|
* 로딩 상태를 쉽게 사용할 수 있는 컴포저블
|
|
* 로딩 카운터 방식으로 여러 비동기 작업을 안전하게 관리합니다.
|
|
*/
|
|
export const useLoading = () => {
|
|
const loadingStore = useLoadingStore();
|
|
|
|
/**
|
|
* 로딩 상태와 함께 비동기 함수를 실행합니다.
|
|
* 함수 실행 중에는 자동으로 로딩 카운터가 증가하고, 완료되면 감소합니다.
|
|
*
|
|
* @param asyncFn 실행할 비동기 함수
|
|
* @param message 로딩 메시지 (선택사항)
|
|
* @returns Promise<T> 비동기 함수의 결과
|
|
*/
|
|
const withLoading = async <T>(
|
|
asyncFn: () => Promise<T>,
|
|
message?: string
|
|
): Promise<T> => {
|
|
loadingStore.startLoading(message);
|
|
try {
|
|
return await asyncFn();
|
|
} finally {
|
|
loadingStore.stopLoading(message);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 로딩 상태를 수동으로 관리할 때 사용합니다.
|
|
*
|
|
* @param message 로딩 메시지 (선택사항)
|
|
* @returns 로딩 종료 함수
|
|
*/
|
|
const startLoading = (message?: string) => {
|
|
loadingStore.startLoading(message);
|
|
return () => loadingStore.stopLoading(message);
|
|
};
|
|
|
|
/**
|
|
* 특정 메시지로 로딩을 시작하고, 해당 메시지로 종료할 수 있는 함수를 반환합니다.
|
|
*
|
|
* @param message 로딩 메시지
|
|
* @returns 로딩 종료 함수
|
|
*/
|
|
const withMessage = (message: string) => {
|
|
loadingStore.startLoading(message);
|
|
return () => loadingStore.stopLoading(message);
|
|
};
|
|
|
|
return {
|
|
// 상태
|
|
isLoading: computed(() => loadingStore.isLoading),
|
|
loadingCount: computed(() => loadingStore.loadingCount),
|
|
currentMessage: computed(() => loadingStore.currentMessage),
|
|
loadingMessages: computed(() => loadingStore.loadingMessages),
|
|
|
|
// 액션
|
|
startLoading,
|
|
stopLoading: loadingStore.stopLoading,
|
|
withLoading,
|
|
withMessage,
|
|
clearAll: loadingStore.clearAllLoading,
|
|
reset: loadingStore.reset,
|
|
};
|
|
};
|