From e21987d1553b94d16cdf339b75b30a7b57176f65 Mon Sep 17 00:00:00 2001 From: franco sanchez Date: Thu, 25 Jul 2024 13:30:32 -0300 Subject: [PATCH] fix: problem with the scroll position in explore --- src/components/AllBooks.tsx | 17 ++++++++++++-- ...ccountActions.tsx => useAccountActions.ts} | 0 src/hooks/{useDebounce.tsx => useDebounce.ts} | 0 ...useGenerateSlug.tsx => useGenerateSlug.ts} | 0 ...useNetworkState.tsx => useNetworkState.ts} | 0 ...etchLocation.tsx => useRefetchLocation.ts} | 0 src/hooks/useScrollRestoration.ts | 23 +++++++++++++++++++ 7 files changed, 38 insertions(+), 2 deletions(-) rename src/hooks/{useAccountActions.tsx => useAccountActions.ts} (100%) rename src/hooks/{useDebounce.tsx => useDebounce.ts} (100%) rename src/hooks/{useGenerateSlug.tsx => useGenerateSlug.ts} (100%) rename src/hooks/{useNetworkState.tsx => useNetworkState.ts} (100%) rename src/hooks/{useRefetchLocation.tsx => useRefetchLocation.ts} (100%) create mode 100644 src/hooks/useScrollRestoration.ts diff --git a/src/components/AllBooks.tsx b/src/components/AllBooks.tsx index e83bf3d..4d12474 100644 --- a/src/components/AllBooks.tsx +++ b/src/components/AllBooks.tsx @@ -1,4 +1,5 @@ import React, { useEffect } from 'react'; +import { ScrollRestoration } from 'react-router-dom'; import { Flex, Spinner, @@ -12,6 +13,7 @@ import { useInView } from 'react-intersection-observer'; import { CardType } from '@components/types'; import { useBooksPaginate } from '@hooks/queries'; +import { useScrollRestoration } from '@hooks/useScrollRestoration'; import { MySimpleGrid } from '@components/MySimpleGrid'; import { Card } from '@components/cards/Card'; import { Aside } from '@components/Aside'; @@ -25,9 +27,19 @@ export function AllBooks() { useBooksPaginate(); let fetchingNextPageUI; + useScrollRestoration(isPending); // Restablecer la posiciĆ³n del scroll al volver de la vista del libro + useEffect(() => { - if (inView) fetchNextPage(); - }, [inView]); + let isMounted = true; + + if (inView && isMounted) { + fetchNextPage(); + } + + return () => { + isMounted = false; + }; + }, [inView, fetchNextPage]); if (isPending) { return ; @@ -66,6 +78,7 @@ export function AllBooks() { return ( <> + { + function handleScroll() { + sessionStorage.setItem(location.key, JSON.stringify(window.scrollY)); + } + + window.addEventListener('scroll', handleScroll); + + const scrollPosition = sessionStorage.getItem(location.key); + if (scrollPosition && !loading) { + window.scrollTo(0, JSON.parse(scrollPosition)); + } + + return () => { + window.removeEventListener('scroll', handleScroll); + }; + }, [location.key, loading]); +}