From 2f0cd24fb8edecac655ac35b7131eaa55ac78cb9 Mon Sep 17 00:00:00 2001 From: ChristoferMendes Date: Sun, 12 May 2024 14:25:13 -0300 Subject: [PATCH] refactor: Improve the structure of useMagnetData function --- .../seeders-and-peers/useMagnetData.tsx | 43 ++++++++++--------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/src/renderer/src/pages/game-details/seeders-and-peers/useMagnetData.tsx b/src/renderer/src/pages/game-details/seeders-and-peers/useMagnetData.tsx index b072ac22..77622e81 100644 --- a/src/renderer/src/pages/game-details/seeders-and-peers/useMagnetData.tsx +++ b/src/renderer/src/pages/game-details/seeders-and-peers/useMagnetData.tsx @@ -1,10 +1,12 @@ -import { useCallback, useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import { TorrentData } from "./types"; const cache: Record = {}; export function useMagnetData(magnet: string) { - const [magnetData, setMagnetData] = useState(cache[magnet] || null); + const [magnetData, setMagnetData] = useState( + cache[magnet] || null + ); const [isLoading, setIsLoading] = useState(() => { if (cache[magnet]) { return false; @@ -40,31 +42,32 @@ export function useMagnetData(magnet: string) { setIsLoading(false); } ); - }, []); + }, [magnet]); - const invalidateCache = useCallback(() => { - const TWO_MINUTES = 2 * 60 * 1000; - const cacheExpiresIn = TWO_MINUTES; - - Object.keys(cache).forEach((key) => { - const lastTracked = cache[key].lastTracked; - - if (!lastTracked) { - return; - } - - if (Date.now() - lastTracked.getTime() > cacheExpiresIn) { - delete cache[key]; - } - }); - }, []); useEffect(() => { + function invalidateCache() { + const TWO_MINUTES = 2 * 60 * 1000; + const cacheExpiresIn = TWO_MINUTES; + + Object.keys(cache).forEach((key) => { + const lastTracked = cache[key].lastTracked; + + if (!lastTracked) { + return; + } + + if (Date.now() - lastTracked.getTime() > cacheExpiresIn) { + delete cache[key]; + } + }); + } + invalidateCache(); return () => { invalidateCache(); - } + }; }, []); return {