Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: persistence of searchParams for leaderboard #151

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import RedditFeed from "@/components/reddit-feed";
import { Metadata } from "next";
import TopRecordedGames from "@/components/recs/top-recorded-games";
import BannerAd from "@/components/ads/bannerAd";
import { Suspense } from "react";

export const metadata: Metadata = {
title: "Home - AoM.gg",
Expand Down Expand Up @@ -34,7 +35,9 @@ export default function Home() {
<div className="flex-1">
<div className="grid grid-cols-1 xl:grid-cols-4 gap-5">
<div className="xl:col-span-3">
<Leaderboard />
<Suspense>
<Leaderboard />
</Suspense>
</div>
<div className="xl:col-span-1 space-y-4">
<FeaturedYoutubeVideos />
Expand Down
20 changes: 19 additions & 1 deletion src/components/data-table-pagination.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import {
import { Table } from "@tanstack/react-table";

import { Button } from "@/components/ui/button";
import { useQueryParams } from "@/hooks/useQueryParams";
import { useSearchParams } from "next/navigation";
import { useEffect } from "react";

interface DataTablePaginationProps<TData> {
table: Table<TData>;
Expand All @@ -15,6 +18,20 @@ interface DataTablePaginationProps<TData> {
export function DataTablePagination<TData>({
table,
}: DataTablePaginationProps<TData>) {
const rowOptions = [50, 100, 200]

const searchParams = useSearchParams();
const rows = searchParams.get("rows");
const queryParams = useQueryParams({ rows: "50" });

useEffect(() => {
if (rowOptions.includes(Number(rows))) {
table.setPageSize(Number(rows))
return
}
table.setPageSize(rowOptions[0])
}, []);

return (
<div className="flex px-2">
{/* Left-aligned content */}
Expand All @@ -26,9 +43,10 @@ export function DataTablePagination<TData>({
value={table.getState().pagination.pageSize}
onChange={(e) => {
table.setPageSize(Number(e.target.value));
queryParams.rows(e.target.value);
}}
>
{[50, 100, 200].map((pageSize) => (
{rowOptions.map((pageSize) => (
<option
className="font-normal text-base"
key={pageSize}
Expand Down
2 changes: 1 addition & 1 deletion src/components/filters/date-build-patch-filter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function DateBuildPatchFilter({
function getValue(build: Build) {
return build.buildNumber.toString();
}
console.log("filterOptions", filterOptions);

return (
<SelectFilter
data={builds}
Expand Down
54 changes: 42 additions & 12 deletions src/components/leaderboard.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,70 @@
"use client";
import { useCallback, useEffect, useState, useMemo } from "react";
import { columns } from "./leaderboardColumns";
import { DataTable } from "./data-table";
import { DataTable, PaginationState } from "./data-table";
import { Card } from "./ui/card";
import { Input } from "./ui/input";
import { debounce } from "@/utils/debounce";
import { Spinner } from "./spinner";
import { ILeaderboardPlayer } from "@/types/LeaderboardPlayer";
import { LeaderboardTypeValues } from "@/types/LeaderBoard";
import { useSearchParams } from "next/navigation";
import { useQueryParams } from "@/hooks/useQueryParams";
import { OnChangeFn } from "@tanstack/react-table";

export function usePagination() {
const [pagination, setPagination] = useState({
pageSize: 50,
pageIndex: 0,
});
const { pageSize, pageIndex } = pagination;
const queryParams = useQueryParams({ page: "1" });
const searchParams = useSearchParams();
const [rows, page] = ["rows", "page"].map((key) => searchParams.get(key));

const getInitialState = () => {
let pageSize = Number(rows) || 50;
let pageIndex = Number(page) - 1 || 0;
if (pageSize < 0) {
pageSize = 50;
}
if (pageIndex < 0) {
pageIndex = 0;
}
return { pageSize, pageIndex };
}

const [pagination, setPagination] = useState(getInitialState());

const onPaginationChange: OnChangeFn<{pageSize: number, pageIndex: number}> = (updater: any) =>{
setPagination((prev) => {
const newState = updater(prev);
queryParams.page((newState.pageIndex + 1).toString());
return { ...newState };
});

}
const { pageSize, pageIndex } = pagination;
return {
limit: pageSize,
onPaginationChange: setPagination,
setPagination,
onPaginationChange,
pagination,
skip: pageSize * pageIndex,
};
}

export default function Leaderboard() {
const searchParams = useSearchParams();
const [type, search] = ["type", "search"].map((key) => searchParams.get(key));

const [leaderboardData, setLeaderboardData] = useState<ILeaderboardPlayer[]>(
[]
);
const [leaderboardType, setLeaderboardType] = useState<number>(
const [leaderboardType, setLeaderboardType] = useState<number>(Number(type) ||
LeaderboardTypeValues["1v1Supremacy"]
);
const [totalRecords, setTotalRecords] = useState(0);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [searchQuery, setSearchQuery] = useState(search || "");
const [initialLoad, setInitialLoad] = useState(true);

const { limit, onPaginationChange, skip, pagination } = usePagination();
const queryParams = useQueryParams({ type: "", page: "1", search: ""});
const { limit, onPaginationChange, setPagination, skip, pagination } = usePagination();

const getLeaderboardData = useCallback(
async (searchQuery: string) => {
Expand Down Expand Up @@ -96,15 +124,17 @@ export default function Leaderboard() {
]);

function handleSearchQueryChange(event: React.ChangeEvent<HTMLInputElement>) {
onPaginationChange({ pageIndex: 0, pageSize: pagination.pageSize });
setPagination({ pageIndex: 0, pageSize: pagination.pageSize });
setSearchQuery(event.target.value);
queryParams.search(event.target.value);
}

const handleLeaderboardTypeChange = (
event: React.ChangeEvent<HTMLSelectElement>
) => {
const selectedType = parseInt(event.target.value);
setLeaderboardType(selectedType);
queryParams.type(selectedType.toString());
};

return (
Expand Down
27 changes: 27 additions & 0 deletions src/hooks/useQueryParams.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useMemo } from 'react';
import { useRouter } from 'next/navigation';


type QueryParams<T extends Record<string, string>> = {
[K in keyof T]: (value: T[K]) => void;
};

export const useQueryParams = <T extends Record<string, string>>(params: T): QueryParams<T> => {
const router = useRouter();

return useMemo(() => {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm new to using useMemo. As I understand it, this is caching the "page" so that it isn't recalculated when navigating back/forward I assume? Let me know if there was another purpose that I missed. Thanks for adding this.

return Object.keys(params).reduce((acc, key) => {
acc[key as keyof T] = (value: T[keyof T]) => {
const searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newUrl = `${window.location.pathname}?${searchParams.toString()}`;
if (value === '') {
newUrl = newUrl.replace(`?${key}=`, '').replace(`&${key}=`, '').replace(`&${key}`, '').replace(`?${key}`, '');
}
window.history.replaceState(null, '', newUrl);
};

return acc;
}, {} as QueryParams<T>);
}, [params, router]);
};