Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

i have this paging system in next.js helpers/useMattersPages.ts 36 import { useEffect,…

  1. User

    i have this paging system in next.js

    helpers/useMattersPages.ts

    36 import { useEffect, useState } from "react"; │
    │ 35 import api from "@/helpers/api"; │
    │ 34 import error from "./error"; │
    │ 33 import { MatterType } from "./types"; │
    │ 32 │
    │ 31 type PropsType<T = MatterType> = { │
    │ 30 │ initialMatters?: T[]; │
    │ 29 │ params?: { [key: string]: unknown }; │
    │ 28 │ endpoint?: string; │
    │ 27 │ initialPage?: number; │
    │ 26 │ pageSize?: number; │
    │ 25 }; │
    │ 24 │
    │ 23 type ReturnType<T = MatterType> = [ │
    │ 22 │ { matters: T[]; loading: boolean; allLoaded: boolean; page: number }, │
    │ 21 │ (newPage: number) => void │
    │ 20 ]; │
    │ 19 │
    │ 18 export default function useMatters<T = MatterType>({ │
    │ 17 │ initialMatters = [], │
    │ 16 │ params = {}, │
    │ 15 │ endpoint = "matters", │
    │ 14 │ initialPage = 1, │
    │ 13 }: PropsType): ReturnType { │
    │ 12 │ const [matters, setMatters] = useState<T[]>(initialMatters); │
    │ 11 │ const [allLoaded, setAllLoaded] = useState(false); │
    │ 10 │ const [loading, setLoading] = useState(false); │
    │ 9 │ const [page, setPage] = useState(initialPage); │
    │ 8 │ │
    │ 7 │ const fetchData = async (page: number) => { │
    │ 6 │ │ setLoading(true); │
    │ 5 │ │ try { │
    │ 4 │ │ │ const { data } = await api.get<T[] | { matters: T[] }>(endpoint, { │
    │ 3 │ │ │ │ params: { ...params, page }, │
    │ 2 │ │ │ }); │
    │ 1 │ │ │ const items = "matters" in data ? data.matters : data; │
    │37 │ │ │ │
    │ 1 │ │ │ // Replace the current matters with the new items │
    │ 2 │ │ │ setMatters(items); │
    │ 3 │ │ │ setLoading(false); │
    │ 4 │ │ │ │
    │ 5 │ │ │ // If there are no items received, we assume all items are loaded │
    │ 6 │ │ │ setAllLoaded(items.length === 0); │
    │ 7 │ │ } catch (e) { │
    │ 8 │ │ │ error(e); │
    │ 9 │ │ │ setLoading(false); │
    │ 10 │ │ } │
    │ 11 │ }; │
    │ 12 │ │
    │ 13 │ useEffect(() => { │
    │ 14 │ │ void fetchData(page); │
    │ 15 │ }, [page]); │
    │ 16 │ │
    │ 17 │ const getMatters = (newPage: number) => { │
    │ 18 │ │ setPage(newPage); │
    │ 19 │ }; │
    │ 20 │ │
    │ 21 │ return [{ matters, loading, allLoaded, page }, getMatters]; │
    │ 22 }

    components/Paging.tsx import React from 'react'; │
    │ 35 │
    │ 34 interface PagingProps { │
    │ 33 │ currentPage: number; │
    │ 32 │ onPageChange: (newPage: number) => void; │
    │ 31 │ hasMore: boolean; │
    │ 30 │ range: number; │
    │ 29 } │
    │ 28 │
    │ 27 const Paging: React.FC = ({ currentPage, onPageChange, hasMore, range }) => { │
    │ 26 │ const generatePageNumbers = () => { │
    │ 25 │ │ const pages = []; │
    │ 24 │ │ const start = Math.max(1, currentPage - 1); │
    │ 23 │ │ for (let i = start; i <= start + range && (i === currentPage || i === start || hasMore); i++) { │
    │ 22 │ │ │ pages.push(i); │
    │ 21 │ │ } │
    │ 20 │ │ return pages; │
    │ 19 │ }; │
    │ 18 │ │
    │ 17 │ const pages = generatePageNumbers(); │
    │ 16 │ │
    │ 15 │ return ( │
    │ 14 │ │ │
    │ 13 │ │ │ <button onClick={() => onPageChange(currentPage - 1)} disabled={currentPage === 1}> │
    │ 12 │ │ │ │ < │
    │ 11 │ │ │ │
    │ 10 │ │ │ │
    │ 9 │ │ │ {pages[0] > 1 && ...} │
    │ 8 │ │ │ │
    │ 7 │ │ │ {pages.map(page => ( │
    │ 6 │ │ │ │ <button │
    │ 5 │ │ │ │ │ key={page} │
    │ 4 │ │ │ │ │ onClick={() => onPageChange(page)} │
    │ 3 │ │ │ │ │ className={currentPage === page ? 'active' : ''} │
    │ 2 │ │ │ │ │ disabled={currentPage === page} │
    │ 1 │ │ │ │ > │
    │37 │ │ │ │ │ {page} │
    │ 1 │ │ │ │ │
    │ 2 │ │ │ ))} │
    │ 3 │ │ │ │
    │ 4 │ │ │ {hasMore && ...} │
    │ 5 │ │ │ │
    │ 6 │ │ │ <button onClick={() => onPageChange(currentPage + 1)} disabled={!hasMore}> │
    │ 7 │ │ │ │ > │
    │ 8 │ │ │ │
    │ 9 │ │ │ │
    │ 10 │ │ │ { │ │ 11 │ │ │ │ .paging { │ │ 12 │ │ │ │ │ display: flex; │ │ 13 │ │ │ │ │ justify-content: center; │ │ 14 │ │ │ │ │ align-items: center; │ │ 15 │ │ │ │ │ margin: 20px 0; │ │ 16 │ │ │ │ } │ │ 17 │ │ │ │ button { │ │ 18 │ │ │ │ │ border: 1px solid #d9d9d9; │ │ 19 │ │ │ │ │ color: #000; │ │ 20 │ │ │ │ │ margin: 0 5px; │ │ 21 │ │ │ │ │ padding: 5px 10px; │ │ 22 │ │ │ │ │ cursor: pointer; │ │ 23 │ │ │ │ │ &:hover:not(:disabled) { │ │ 24 │ │ │ │ │ │ transition: 0.3s; │ │ 25 │ │ │ │ │ │ background: #d9d9d9; │ │ 26 │ │ │ │ │ } │ │ 27 │ │ │ │ } │ │ 28 │ │ │ │ button:disabled { │ │ 29 │ │ │ │ │ color: #d9d9d9; │ │ 30 │ │ │ │ │ cursor: not-allowed; │ │ 31 │ │ │ │ } │ │ 32 │ │ │ │ .active { │ │ 33 │ │ │ │ │ color: #f4213b !important; │ │ 34 │ │ │ │ │ border: 1px solid #f4213b; │ │ 35 │ │ │ │ } │ │ 36 │ │ │ │ span { │ │ 37 │ │ │ │ │ font-weight: 600; │ │ 38 │ │ │ │ │ margin: 0 5px; │ │ 39 │ │ │ │ │ position: relative; │ │ 40 │ │ │ │ │ top: -4px; │ │ 41 │ │ │ │ │ color: #d9d9d9; │ │ 42 │ │ │ │ } │ │ 43 │ │ │} │
    │ 45 │ ); │
    │ 46 }; │
    │ 47 │
    │ 48 export default Paging;

    pages/index.tsx

    import { MainPageDataType, MatterType, TagType } from "@/helpers/types"; │
    │ 55 import { GetServerSideProps, NextPage } from "next"; │
    │ 54 import { getMainPageData } from "@/helpers/getInstance"; │
    │ 53 import { usePlatform } from "@/helpers/platformContext"; │
    │ 52 import MattersList from "@/components/MattersList"; │
    │ 51 import Loading from "@/components/Loading"; │
    │ 50 import useMatters from "@/helpers/useMattersPaged"; │
    │ 49 import { serverApi } from "@/helpers/api"; │
    │ 48 import { useDevice } from "@/helpers/deviceContext"; │
    │ 47 import dynamic from "next/dynamic"; │
    │ 46 import Banner from "@/components/Banner"; │
    │ 45 import useToplineTransparenty from "@/helpers/useToplineTransparenty"; │
    │ 44 import EditButton from "@/components/EditButton"; │
    │ 43 import { SlugEnum } from "@/helpers/slugEnums"; │
    │ 42 import withDateToken from "@/helpers/withDateToken"; │
    │ 41 import Paging from "@/components/Paging"; │
    │ 40 import { useRouter } from "next/router"; │
    │ 39 │
    │ 38 const MobileStory = dynamic(() => import("@/components/IndexPage/MobileStory")); │
    │ 37 const DayPictureMobile = dynamic( │
    │ 36 │ () => import("@/components/IndexPage/DayPictureMobile") │
    │ 35 ); │
    │ 34 const DayPictureDesktop = dynamic( │
    │ 33 │ () => import("@/components/IndexPage/DayPictureDesktop") │
    │ 32 ); │
    │ 31 const MobileBottomTabs = dynamic(() => import("@/components/MobileBottomTabs")); │
    │ 30 │
    │ 29 const endpoint = "main_page/matters"; │
    │ 28 type PropsType = MainPageDataType & { │
    │ 27 │ initialMatters: MatterType[]; │
    │ 26 }; │
    │ 25 │
    │ 24 const IndexPage: NextPage = ({ │
    │ 23 │ day_picture, │
    │ 22 │ stories, │
    │ 21 │ initialMatters, │
    │ 20 │ day_picture_type, │
    │ 19 }) => { │
    │ 18 │ const router = useRouter(); │
    │ 17 │ const initialPage = parseInt(router.query.page as string, 10) || 1; │
    │ 16 │ const { isMobile } = useDevice(); │
    │ 15 │ const { live_config, h1_title_on_main_page, settings_custom } = usePlatform(); │
    │ 14 │ const secondStory = stories ? stories[1]?.story : undefined; │
    │ 13 │ let firstItem: MatterType | TagType | undefined = day_picture[0]?.matter?.path │
    │ 12 │ │ ? day_picture[0]?.matter │
    │ 11 │ │ : undefined; │
    │ 10 │ if (stories && stories[0]?.story) firstItem = stories[0].story; │
    │ 9 │ if (live_config && (settings_custom.live_mainpage ?? true)) { │
    │ 8 │ │ firstItem = live_config; │
    │ 7 │ } │
    │ 6 │ │
    │ 5 │ const otherItems = day_picture │
    │ 4 │ │ ?.filter((el) => el.matter?.path && el.matter?.path !== firstItem?.path) │
    │ 3 │ │ .map((el) => el.matter) │
    │ 2 │ │ .slice(0, 5); │
    │ 1 │ │
    │57 │ const [{ matters, loading, allLoaded, page }, getMatters] = useMatters({ │
    │ 1 │ │ initialMatters, │
    │ 2 │ │ endpoint, │
    │ 3 │ │ initialPage, │
    │ 4 │ }); │
    │ 5 │ │
    │ 6 │ useToplineTransparenty(!!day_picture && !!day_picture[0]?.matter?.path); // картины дня может не быть при ошибках на стороне api │
    │ 7 │ │
    │ 8 │ const handlePageChange = (newPage: number) => { │
    │ 9 │ │ getMatters(newPage); │
    │ 10 │ │ void router.push(/?page=${newPage}, undefined, { shallow: true }); │
    │ 11 │ };
    return ( │
    │ 8 │ │ <> │
    │ 7 │ │ │ {isMobile && firstItem ? ( │
    │ 6 │ │ │ │ <> │
    │ 5 │ │ │ │ │ │
    │ 4 │ │ │ │ │ <DayPictureMobile │
    │ 3 │ │ │ │ │ │ firstItem={firstItem} │
    │ 2 │ │ │ │ │ │ otherItems={otherItems} │
    │ 1 │ │ │ │ │ │ extraPaddingBottom={!!secondStory} │
    │79 │ │ │ │ │ /> │
    │ 1 │ │ │ │ </> │
    │ 2 │ │ │ ) : ( │
    │ 3 │ │ │ │ firstItem && ( │
    │ 4 │ │ │ │ │ <DayPictureDesktop │
    │ 5 │ │ │ │ │ │ firstItem={firstItem} │
    │ 6 │ │ │ │ │ │ otherItems={otherItems} │
    │ 7 │ │ │ │ │ │ secondStory={secondStory} │
    │ 8 │ │ │ │ │ │ dayPictureType={day_picture_type} │
    │ 9 │ │ │ │ │ /> │
    │ 10 │ │ │ │ ) │
    │ 11 │ │ │ )} │
    │ 12 │ │ │ │
    │ 13 │ │ │ │ {isMobile && secondStory && } │
    │ 14 │ │ │ │
    │ 15 │ │ │ │
    │ 16 │ │ │ <Banner │
    │ 17 │ │ │ │ className="max-w-[826px] mx-auto" │
    │ 18 │ │ │ │ slug={SlugEnum.mainpage_story_after_2} │
    │ 19 │ │ │ /> │
    │ 20 │ │ │ │
    │ 21 │ │ │ │ <h1 className={"text-lg font-bold mb-[19px] lg:font-serif lg:text-[35px] lg:mb-[38px] max-w-[826px] mx-auto" + (isMobile ? (secondStory ? " mt-[10│
    │ px]" : " mt-[30px]") : "")}> │
    │ 22 │ │ │ │ │ {withDateToken(h1_title_on_main_page)} │
    │ 23 │ │ │ │ │
    │ 24 │ │ │ │ <MattersList │
    │ 25 │ │ │ │ │ matters={matters} │
    │ 26 │ │ │ │ │ bannerSlug={SlugEnum.mainpage_feed} │
    │ 27 │ │ │ │ │ additionalBannerSlug={SlugEnum.mainpage_feed_3} │
    │ 28 │ │ │ │ │ showPeriod={false} │
    │ 29 │ │ │ │ │ initialMattersLength={ │
    │ 30 │ │ │ │ │ │ initialMatters?.length ? initialMatters.length : 0 │
    │ 31 │ │ │ │ │ } │
    │ 32 │ │ │ │ /> │
    │ 33 │ │ │ │ <Paging │
    │ 34 │ │ │ │ │ currentPage={page} │
    │ 35 │ │ │ │ │ onPageChange={handlePageChange} │
    │ 36 │ │ │ │ │ hasMore={!allLoaded} │
    │ 37 │ │ │ │ │ range={2} // Change as needed │
    │ 38 │ │ │ │ /> │
    │ 39 │ │ │ │ {loading && } │
    │ 40 │ │ │ │ <EditButton url={"/admin/publishers/homepage"} /> │
    │ 41 │ │ │ │
    │ 42 │ │ </> │
    │ 43 │ ); │
    │ 44 }; │
    │ 45 │
    │ 46 export default IndexPage; │
    │ 47

    export const getServerSideProps: GetServerSideProps = async ({ │
    │ 49 │ req, │
    │ 50 }) => { │
    │ 51 │ const results = await Promise.all([ │
    │ 52 │ │ getMainPageData(req), │
    │ 53 │ │ serverApi<MatterType[]>(endpoint, { req }, []), │
    │ 54 │ ]); │
    │ 55 │ │
    │ 56 │ return "notFound" in results[0] || "notFound" in results[1] │
    │ 57 │ │ ? { notFound: true } │
    │ 58 │ │ : { │
    │ 59 │ │ │ props: { │
    │ 60 │ │ │ │ ...results[0].mainPageData, │
    │ 61 │ │ │ │ initialMatters: results[1].data, │
    │ 62 │ │ │ }, │
    │ 63 │ │ }; │
    │ 64 }; │
    │~

    it works well, but when i switch page, every time i see contents of first page, which in a second replaced by needed page content, like blinking first page, before new content is loaded and showed. how to fix this?

  2. Assistant

    The issue you're experiencing is likely due to the fact that the state and the page rendered initially don't match the state intended for the new page between client-side transitions. When you invoke a page change, the useMatters hook is called, and it fetches new data, but the previous state is rendered first before the new data is loaded, resulting in the flicker you observe.

    To address this issue, you can consider clearing the matters state before fetching new data or while the data is being fetched, so that during the fetch, the old content is not shown. You can also consider showing a loading indicator or a placeholder during this time to improve the user experience. Here's how you can update your hook and component to handle this:

    In useMatters Hook

    You can clear the existing matters when starting a new fetch:

    const fetchData = async (page: number) => {
        setLoading(true);
        // Clear the current matters to prevent flickering
        setMatters([]);
        try {
            const { data } = await api.get<T[] | { matters: T[] }>(endpoint, {
                params: { ...params, page },
            });
            const items = "matters" in data ? data.matters : data;
            setMatters(items);
            setLoading(false);
    
            // If there are no items received, we assume all items are loaded
            setAllLoaded(items.length === 0);
        } catch (e) {
            error(e);
            setLoading(false);
        }
    };
    

    In IndexPage

    Ensure you're handling loading state with a placeholder or loader during data fetching, which you seem to be handling with a Loading component already, so just ensure its placement makes sense in your render flow:

    return (
        <>
            {isMobile && firstItem ? (
                <>
                    <MobileBottomTabs />
                    <DayPictureMobile
                        firstItem={firstItem}
                        otherItems={otherItems}
                        extraPaddingBottom={!!secondStory}
                    />
                </>
            ) : (
                firstItem && (
                    <DayPictureDesktop
                        firstItem={firstItem}
                        otherItems={otherItems}
                        secondStory={secondStory}
                        dayPictureType={day_picture_type}
                    />
                )
            )}
            <div className="container">
                {isMobile && secondStory && <MobileStory item={secondStory} />}
            </div>
            <Banner className="my-4" slug={SlugEnum.mainpage_story_after} />
            <Banner className="max-w-[826px] mx-auto" slug={SlugEnum.mainpage_story_after_2} />
            <div className="container">
                <h1 className={"text-lg font-bold mb-[19px] lg:font-serif lg:text-[35px] lg:mb-[38px] max-w-[826px] mx-auto" + (isMobile ? (secondStory ? " mt-[10px]" : " mt-[30px]") : "")}>
                    {withDateToken(h1_title_on_main_page)}
                </h1>
                <MattersList
                    matters={matters}
                    bannerSlug={SlugEnum.mainpage_feed}
                    additionalBannerSlug={SlugEnum.mainpage_feed_3}
                    showPeriod={false}
                    initialMattersLength={initialMatters?.length ? initialMatters.length : 0}
                />
                <Paging
                    currentPage={page}
                    onPageChange={handlePageChange}
                    hasMore={!allLoaded}
                    range={2} // Change as needed
                />
                {loading && <Loading />}
                <EditButton url={"/admin/publishers/homepage"} />
            </div>
        </>
    );
    

    Considerations

    1. Data Fetching Strategy: The described method effectively hides old data but might not be optimal if displaying some content is preferable to no content. You could alternatively provide skeletons or load states in the UI.

    2. Consistency: Ensure that Page component and state hooks remain consistent, with no unexpected cross-interaction. Use of useEffect for fetches should align with expectations for updating component lifecycle without redundant renders.

    3. Updates to Router: When routing with router.push, ensure the shallow routing properly reflects only necessary updates and components that depend on knowing page status correctly track state.

    4. Performance: This method will create a momentary blank screen which can be mitigated by using spinners or skeleton loaders to ensure users aren't seeing nothing while waiting for data to load.

  3. User

    yeah, it helps, thank you! how to rewind page to start of the contents, when new page is loaded?

  4. Assistant

    To scroll to the top of the content when you load a new page, you can use a couple of different approaches. In a React component like you're working with, you have the ability to programmatically control the scroll position using the DOM's window.scrollTo method.

    Here's how you can implement this after changing the page:

    Updating the Page Scroll in handlePageChange Function

    Edit your handlePageChange function inside your IndexPage component to scroll to the top whenever a new page is about to be displayed:

    const handlePageChange = (newPage: number) => {
        // Scroll to top of the page
        window.scrollTo({ top: 0, behavior: 'smooth' });
        
        // Fetch the matters for the selected page
        getMatters(newPage);
        
        // Update the URL with the new page number
        void router.push(`/?page=${newPage}`, undefined, { shallow: true });
    };
    

    Explanation

    • window.scrollTo(): This method is used to scroll the document to a specified location. By setting top: 0, you ensure the page scrolls to the top.
    • behavior: 'smooth': This optional parameter adds a smooth scrolling animation. You can remove this if you prefer the scrolling to be instantaneous.

    Notes

    1. User Experience: Providing a smooth scroll can improve the user experience because abrupt changes can be jarring. However, use with consideration to the overall feel of the application.

    2. Multiple Method Calls: If getMatters or router.push are asynchronous or induce loading states, make sure their resultant state aligns with expected page conditions (e.g., ensuring getMatters is called first might be your desired flow).

    3. Enhancements: Depending on your app's structure, you might tweak placement of scroll logic for nuanced style, such as within useMatters hook side-effects if inter-component communication grows complex. If dealing with specific sections, ensure the specific container's positioning is correctly targeted.

    4. Adjustments for Container-Specific Scrolling: If your pages are loaded inside containers that don’t occupy the whole window height, you might need to scroll specific container elements instead of window. In this case, substitute window.scrollTo with a reference to the container and use scrollIntoView or similar methods to adjust scroll focus.

  5. User

    but i do not want to scroll to top, only to top of the changed block with new items loaded

  6. Assistant

    If you want to scroll to the top of a specific section of your page (e.g., the list of items), you can achieve this by using React's ref system to get a reference to the container you want to scroll to. Here’s how you can do it:

    Step-by-Step Guide

    1. Add a Ref to the Container:

    Create a ref using useRef and assign it to the container element that holds your list of items (MattersList in your case).

    1. Update handlePageChange Function:

    Use the ref to scroll to the top of that container rather than the whole page when new data is loaded.

    Here's how you can do it:

    Code Implementation

    Add a ref to the container you want to scroll into view:

    import { useRef } from "react";
    
    const IndexPage: NextPage<PropsType> = ({ day_picture, stories, initialMatters, day_picture_type }) => {
        const router = useRouter();
        const initialPage = parseInt(router.query.page as string, 10) || 1;
        const { isMobile } = useDevice();
        const { live_config, h1_title_on_main_page, settings_custom } = usePlatform();
        const mattersRef = useRef<HTMLDivElement>(null); // Using ref to target the container
    
        // ... rest of your component ...
    
        const handlePageChange = (newPage: number) => {
            // Scroll to the top of the matters section
            if (mattersRef.current) {
                mattersRef.current.scrollIntoView({ behavior: 'smooth' });
            }
            
            getMatters(newPage);
            void router.push(`/?page=${newPage}`, undefined, { shallow: true });
        };
    
        return (
            <>
                {/* Rest of your code */}
                
                <div ref={mattersRef} className="container">
                    <h1 className={"text-lg font-bold mb-[19px] lg:font-serif lg:text-[35px] lg:mb-[38px] max-w-[826px] mx-auto" + (isMobile ? (secondStory ? " mt-[10px]" : " mt-[30px]") : "")}>
                        {withDateToken(h1_title_on_main_page)}
                    </h1>
                    <MattersList
                        matters={matters}
                        bannerSlug={SlugEnum.mainpage_feed}
                        additionalBannerSlug={SlugEnum.mainpage_feed_3}
                        showPeriod={false}
                        initialMattersLength={initialMatters?.length ? initialMatters.length : 0}
                    />
                    <Paging
                        currentPage={page}
                        onPageChange={handlePageChange}
                        hasMore={!allLoaded}
                        range={2} // Change as needed
                    />
                    {loading && <Loading />}
                    <EditButton url={"/admin/publishers/homepage"} />
                </div>
                
                {/* Rest of your code */}
            </>
        );
    };
    

    Explanation

    • useRef: This hook creates a mutable object which does not trigger re-renders when it’s changed. It's perfect for storing a reference to a DOM node (<div> in this case).

    • scrollIntoView: This method scrolls the specific element into the view. The option { behavior: 'smooth' } will make it scroll smoothly, which is usually a better user experience. Removing it will result in immediate scrolling.

    Considerations

    1. Ensure Ref Correctness: Make sure the ref is correctly assigned to the element you want to scroll into view. If the container hierarchy changes, adjust the ref accordingly.

    2. Rendering Strategy: This solution assumes you want the viewport to display the top of the specific element after a page changes. Adjust behavior if specific page layout needs differ or if accommodating mobile interfaces (e.g. screen-height constraints are present).

    3. Browser Compatibility: scrollIntoView works with most modern browsers, but if you need to support very old browsers, you may need a polyfill or an alternative method like controlling scrollTop directly with an offset calculation.