20260624214849

This commit is contained in:
oneao committed 2026-06-24 21:48:49 +08:00
1 parent 513a991b57
commit 3795acb9c7
167 files changed
+14779 -3726

No files matched your search

+61
View File
@@ -0,0 +1,61 @@
import { useState, useCallback, useRef } from "react";
import { toast } from "sonner-native";
interface StopOptions {
type?: "success" | "error" | "none";
message?: string;
}
export function useLoading() {
const [isLoading, setIsLoading] = useState(false);
const toastIdRef = useRef<string | number | null>(null);
const startLoading = useCallback((message: string = "加载中...") => {
setIsLoading(true);
const id = toast.loading(message);
toastIdRef.current = id;
return id;
}, []);
const stopLoading = useCallback((options?: StopOptions) => {
setIsLoading(false);
const id = toastIdRef.current;
if (id) {
if (options?.type === "success") {
toast.success(options.message || "操作成功", { id });
} else if (options?.type === "error") {
toast.error(options.message || "操作失败", { id });
} else {
toast.dismiss(id);
}
toastIdRef.current = null;
}
}, []);
const withLoading = useCallback(
async <T,>(
promise: Promise<T>,
loadingMessage: string = "加载中...",
successMessage?: string,
errorMessage?: string
): Promise<T> => {
const id = startLoading(loadingMessage);
try {
const result = await promise;
stopLoading({ type: "success", message: successMessage || "操作成功" });
return result;
} catch (error) {
stopLoading({ type: "error", message: errorMessage || "操作失败" });
throw error;
}
},
[startLoading, stopLoading]
);
return {
isLoading,
startLoading,
stopLoading,
withLoading,
};
}