fix: user info api repeat call
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import { createContext, useContext, useMemo, ReactNode, useCallback, useEffect, useReducer } from 'react';
|
import { createContext, useContext, useMemo, ReactNode, useCallback, useEffect, useReducer, useRef } from 'react';
|
||||||
import { authService } from '../lib/authService';
|
import { authService } from '../lib/authService';
|
||||||
import { ApiErrorMessages } from '../types/api';
|
import { ApiErrorMessages } from '../types/api';
|
||||||
import type { GoogleOAuthCallbackRequest, UserInfo } from '../types/api';
|
import type { GoogleOAuthCallbackRequest, UserInfo } from '../types/api';
|
||||||
@@ -147,20 +147,25 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
dispatch({ type: 'SIGN_OUT' });
|
dispatch({ type: 'SIGN_OUT' });
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
const syncedTokenRef = useRef<string | null>(null);
|
||||||
let cancelled = false;
|
|
||||||
let hasSynced = false;
|
|
||||||
|
|
||||||
const syncUserProfile = async () => {
|
useEffect(() => {
|
||||||
const currentUser = state.user;
|
const currentUser = state.user;
|
||||||
const currentToken = state.token;
|
const currentToken = state.token;
|
||||||
|
|
||||||
if (!currentUser || !currentToken || hasSynced) {
|
if (!currentUser || !currentToken) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
hasSynced = true;
|
// 已经为当前 token 同步过,跳过(防止 StrictMode 双调用或 effect 重复执行)
|
||||||
|
if (syncedTokenRef.current === currentToken) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
syncedTokenRef.current = currentToken;
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
const syncUserProfile = async () => {
|
||||||
try {
|
try {
|
||||||
const profile = await authService.getUserInfo();
|
const profile = await authService.getUserInfo();
|
||||||
if (cancelled) {
|
if (cancelled) {
|
||||||
@@ -175,6 +180,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
// Keep token-derived identity if profile sync fails.
|
// Keep token-derived identity if profile sync fails.
|
||||||
|
if (!cancelled) {
|
||||||
|
// 请求失败时重置,允许下次挂载时重试
|
||||||
|
syncedTokenRef.current = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user