From d868c695143c5f5960f353ed96d74b17104c342f Mon Sep 17 00:00:00 2001 From: amalv <1252707+amalv@users.noreply.github.com> Date: Fri, 29 Dec 2023 11:28:13 +0100 Subject: [PATCH] fix: reset lastPageReached state on search change for infinite scrolling --- src/apolloClient.ts | 2 +- .../components/Books/hooks/useBooks.ts | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/apolloClient.ts b/src/apolloClient.ts index 6ba8b90..6bc3c00 100644 --- a/src/apolloClient.ts +++ b/src/apolloClient.ts @@ -7,7 +7,7 @@ import { import { setContext } from "@apollo/client/link/context"; export const darkModeVar = makeVar( - window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches + window?.matchMedia("(prefers-color-scheme: dark)")?.matches ); const API_URL = diff --git a/src/components/LibraryPage/components/Books/hooks/useBooks.ts b/src/components/LibraryPage/components/Books/hooks/useBooks.ts index 8e90da3..4c9dc15 100644 --- a/src/components/LibraryPage/components/Books/hooks/useBooks.ts +++ b/src/components/LibraryPage/components/Books/hooks/useBooks.ts @@ -100,12 +100,12 @@ export const useBooks = ({ search, limit }: UseBooksProps) => { const [lastPageReached, setLastPageReached] = useState(false); const [isErrorSnackbarOpen, setIsErrorSnackbarOpen] = useState(false); // Fetch books - const { loading, error, data, fetchMore } = useQuery( - BOOKS_QUERY, - { - variables: { title: search, author: search, limit, cursor: "0" }, - } - ); + const { loading, error, data, fetchMore, refetch } = useQuery< + BooksData, + BooksVars + >(BOOKS_QUERY, { + variables: { title: search, author: search, limit, cursor: "0" }, + }); useEffect(() => { if (error) { @@ -113,6 +113,12 @@ export const useBooks = ({ search, limit }: UseBooksProps) => { } }, [error]); + useEffect(() => { + setLastPageReached(false); + lastPageReachedRef.current = false; + refetch({ title: search, author: search, limit, cursor: "0" }); + }, [search, refetch, limit]); + const handleCloseSnackbar = getCloseSnackbarHandler(setIsErrorSnackbarOpen); const updateQuery = getUpdateQuery(setLastPageReached); const loader = useRef(null);