From 778bc276e2268e3d162547aac696b838a5e30e42 Mon Sep 17 00:00:00 2001 From: Aamir Azad <82281117+aamirazad@users.noreply.github.com> Date: Sat, 6 Jul 2024 13:14:26 -0400 Subject: [PATCH] fix: only download the pdf once (#50) This PR addresses an issue where multiple fetch calls were being made in the DocumentViewer component. A new useRef hook (fetchDataCalledRef) is introduced to ensure the fetchData function is called only once. This prevents potential performance issues by avoiding duplicate network requests. --- src/components/document-viewer.tsx | 43 +++++++++++++++++------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/src/components/document-viewer.tsx b/src/components/document-viewer.tsx index ae9a853..96b9d3e 100644 --- a/src/components/document-viewer.tsx +++ b/src/components/document-viewer.tsx @@ -1,7 +1,6 @@ "use client"; -import { useState, useEffect } from "react"; -import LoadingSpinner from "@/components/loading-spinner"; +import { useState, useEffect, useRef } from "react"; import { Button } from "./ui/button"; import { useRouter } from "next/navigation"; import { getUserData } from "@/app/actions"; @@ -40,6 +39,7 @@ export default function DocumentViewer(props: { id: number }) { const [pdfUrl, setPdfUrl] = useState(null); const [loading, setLoading] = useState(true); + const fetchDataCalledRef = useRef(false); const SkeletonLoader = () => (
@@ -65,27 +65,32 @@ export default function DocumentViewer(props: { id: number }) { ); useEffect(() => { - const fetchData = async () => { - setLoading(true); + if (!fetchDataCalledRef.current) { + const fetchData = async () => { + setLoading(true); - try { - const objectUrl = await getPaperlessDocument(props.id); - if (objectUrl) { - setPdfUrl(objectUrl); - } else { + try { + const objectUrl = await getPaperlessDocument(props.id); + if (objectUrl) { + setPdfUrl(objectUrl); + } else { + setPdfUrl(null); + } + } catch (error) { + console.error("An error occurred:", error); setPdfUrl(null); + } finally { + setLoading(false); } - } catch (error) { + }; + + fetchData().catch((error) => { console.error("An error occurred:", error); - setPdfUrl(null); - } finally { - setLoading(false); - } - }; - fetchData().catch((error) => { - console.error("An error occurred:", error); - }); - }, [props.id]); // Dependency array to refetch if id changes + }); + + fetchDataCalledRef.current = true; // Mark as fetched + } + }, [props.id]); // Include props.id in the dependency array if refetch is needed on id change if (loading) { return ;