Skip to content
Snippets Groups Projects
page.tsx 2.58 KiB
Newer Older
Yusuf Akgül's avatar
Yusuf Akgül committed
"use client"

import Game from "@/components/Game";
import Search from "@/components/Search";
import { getBaseURL } from "@/lib/utils";
import { IGame } from "@/types/types";
import { Card, CardContent, Grid, Stack } from "@mui/material";
import { Fragment } from "react";
import InfiniteScroll from "react-infinite-scroll-component";
import { useInfiniteQuery } from "react-query";

// renders a list of games infinitely (presumably)
export default function GamesPage() {
    const {
        data,
        error,
        fetchNextPage,
        hasNextPage,
        isFetching,
        isFetchingNextPage,
        status,
    } = useInfiniteQuery(
        'infiniteGames',
        async ({ pageParam = 1 }) =>
            await fetch(
                `${getBaseURL()}/api/games/?page=${pageParam}`,
                { cache: 'force-cache', }
            ).then((result) => result.json() as Promise<IGame[]>),
        {
            getNextPageParam: (lastPage, pages) => {
                return lastPage.length > 0 ? pages.length + 1 : undefined;
            },
        }
    );

    return (
        <Stack spacing={2}>
            <Search />
            <Card>
                <CardContent>
                    {status === 'success' && (
                        <InfiniteScroll
                            dataLength={data?.pages.length * 20}
                            next={fetchNextPage}
                            hasMore={hasNextPage ? true : false}
                            loader={<h4>Loading...</h4>}
                            endMessage={
                                <p style={{ textAlign: 'center' }}>
                                    <b>Yay! You have seen it all</b>
                                </p>
                            }
                        >
                            <Grid container spacing={2} justifyContent="center">
                                {data?.pages.map((page, i) => (
                                    <Fragment key={i}>
                                        {page.map((game: IGame) => (
                                            <Grid item xs={12} ss={6} sm={4} md={3} lg={2} key={game.id}>
                                                <Game id={game.id} name={game.name} cover={game.cover} key={game.id} />
                                            </Grid>
                                        ))}
                                    </Fragment>
                                ))}
                            </Grid>
                        </InfiniteScroll>
                    )}
                </CardContent>
            </Card>
        </Stack>
    )
}