From 15f71cd9b2695db80ab0c742c656814478ca6eb0 Mon Sep 17 00:00:00 2001 From: Julien Froidefond Date: Tue, 4 Mar 2025 21:45:39 +0100 Subject: [PATCH] fix: loading page now stands up for ending fetches --- src/components/ui/loading-bar.tsx | 40 +++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/src/components/ui/loading-bar.tsx b/src/components/ui/loading-bar.tsx index e631d9d..d870e55 100644 --- a/src/components/ui/loading-bar.tsx +++ b/src/components/ui/loading-bar.tsx @@ -1,12 +1,13 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useState, useRef } from "react"; import { cn } from "@/lib/utils"; import { Loader2 } from "lucide-react"; export function LoadingBar() { const [isLoading, setIsLoading] = useState(false); const [shouldRender, setShouldRender] = useState(false); + const pendingRequestsRef = useRef(0); useEffect(() => { if (isLoading) { @@ -26,7 +27,9 @@ export function LoadingBar() { const handleStop = () => { setTimeout(() => { - setIsLoading(false); + if (pendingRequestsRef.current === 0) { + setIsLoading(false); + } }, 300); }; @@ -39,6 +42,39 @@ export function LoadingBar() { }; }, []); + useEffect(() => { + const originalFetch = window.fetch; + + window.fetch = async function(...args) { + const url = args[0].toString(); + const isStaticRequest = /\.(css|js|png|jpg|jpeg|gif|webp|svg|ico|mp3|mp4|webm|ttf|woff|woff2)$/.test(url); + + if (!isStaticRequest) { + pendingRequestsRef.current++; + setIsLoading(true); + } + + try { + const response = await originalFetch.apply(this, args); + return response; + } finally { + if (!isStaticRequest) { + pendingRequestsRef.current = Math.max(0, pendingRequestsRef.current - 1); + + if (pendingRequestsRef.current === 0) { + setTimeout(() => { + setIsLoading(false); + }, 200); + } + } + } + }; + + return () => { + window.fetch = originalFetch; + }; + }, []); + if (!shouldRender) return null; return (