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