40 lines
949 B
TypeScript
40 lines
949 B
TypeScript
import { useCallback, useEffect, useState } from "react";
|
|
|
|
import { loginNoteApi, type NoteAuth } from "@/core/note/auth";
|
|
|
|
export function useNoteAuth() {
|
|
const [auth, setAuth] = useState<NoteAuth | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const refreshAuth = useCallback(async () => {
|
|
setLoading(true);
|
|
setError(null);
|
|
try {
|
|
const nextAuth = await loginNoteApi();
|
|
setAuth(nextAuth);
|
|
return nextAuth;
|
|
} catch (err) {
|
|
const message =
|
|
err instanceof Error ? err.message : "笔记登录失败,请稍后重试";
|
|
setError(message);
|
|
throw err;
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
void refreshAuth().catch(() => {
|
|
// 错误已在 refreshAuth 中写入 state
|
|
});
|
|
}, [refreshAuth]);
|
|
|
|
return {
|
|
auth,
|
|
loading,
|
|
error,
|
|
refreshAuth,
|
|
};
|
|
}
|