From ab96e7243ea537ecf86eebf7c6a8bfe815d18264 Mon Sep 17 00:00:00 2001 From: Aamir Azad Date: Sat, 29 Jun 2024 11:28:01 +0530 Subject: [PATCH] fix: only download the pdf once --- 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 ;