mirror of
https://github.com/Monadical-SAS/reflector.git
synced 2025-12-21 04:39:06 +00:00
fix: resolve authentication race condition with React Query
Previously, API calls were being made before the auth token was configured, causing initial 401 errors that would retry with 200 after token setup. Changes: - Add global auth readiness tracking in apiClient - Create useAuthReady hook that checks both session and token state - Update all API hooks to use isAuthReady instead of just session status - Add AuthWrapper component at layout level for consistent loading UX - Show spinner while authentication initializes across all pages This ensures API calls only fire after authentication is fully configured, eliminating the 401/retry pattern and improving user experience.
This commit is contained in:
43
www/app/lib/useAuthReady.ts
Normal file
43
www/app/lib/useAuthReady.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import useSessionStatus from "./useSessionStatus";
|
||||
import { isAuthConfigured } from "./apiClient";
|
||||
|
||||
/**
|
||||
* Hook to check if authentication is fully ready.
|
||||
* This ensures both the session is authenticated AND the API client token is configured.
|
||||
* Prevents race conditions where React Query fires requests before the token is set.
|
||||
*/
|
||||
export default function useAuthReady() {
|
||||
const { status, isAuthenticated } = useSessionStatus();
|
||||
const [authReady, setAuthReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Check if both session is authenticated and token is configured
|
||||
const checkAuthReady = () => {
|
||||
const ready = isAuthenticated && isAuthConfigured();
|
||||
setAuthReady(ready);
|
||||
};
|
||||
|
||||
// Check immediately
|
||||
checkAuthReady();
|
||||
|
||||
// Also check periodically for a short time to catch async updates
|
||||
const interval = setInterval(checkAuthReady, 100);
|
||||
|
||||
// Stop checking after 2 seconds (auth should be ready by then)
|
||||
const timeout = setTimeout(() => clearInterval(interval), 2000);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}, [isAuthenticated]);
|
||||
|
||||
return {
|
||||
isAuthReady: authReady,
|
||||
isLoading: status === "loading",
|
||||
isAuthenticated,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user