Skip to content

Commit

Permalink
fix: problem with the scroll position in explore
Browse files Browse the repository at this point in the history
  • Loading branch information
Franqsanz committed Jul 25, 2024
1 parent 48f37b7 commit e21987d
Show file tree
Hide file tree
Showing 7 changed files with 38 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/components/AllBooks.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useEffect } from 'react';
import { ScrollRestoration } from 'react-router-dom';
import {
Flex,
Spinner,
Expand All @@ -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';
Expand All @@ -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 <SkeletonAllBooks showTags={false} />;
Expand Down Expand Up @@ -66,6 +78,7 @@ export function AllBooks() {

return (
<>
<ScrollRestoration />
<Flex
as='article'
direction={{ base: 'column', md: 'row' }}
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
23 changes: 23 additions & 0 deletions src/hooks/useScrollRestoration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

export function useScrollRestoration(loading) {
const location = useLocation();

useEffect(() => {
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]);
}

0 comments on commit e21987d

Please sign in to comment.