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

#281 Fix url search query params #282

Open
wants to merge 5 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
4 changes: 2 additions & 2 deletions apps/web/src/components/inputs/inputs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import { useDebouncedValue } from "@mantine/hooks";
import { FC, useCallback, useState } from "react";
import { useInputsConnectionQuery } from "../../graphql/explorer/hooks/queries";
import { InputOrderByInput } from "../../graphql/explorer/types";
import { useQueryParams } from "../../hooks/useQueryParams";
import getConfiguredChainId from "../../lib/getConfiguredChain";
import { checkQuery } from "../../lib/query";
import InputsTable from "../inputs/inputsTable";
import Paginated from "../paginated";
import Search from "../search";
import { useUrlSearchParams } from "../../hooks/useUrlSearchParams";

export type InputsProps = {
orderBy?: InputOrderByInput;
Expand All @@ -22,7 +22,7 @@ const Inputs: FC<InputsProps> = ({
applicationId,
}) => {
const chainId = getConfiguredChainId();
const { query: urlQuery } = useQueryParams();
const [{ query: urlQuery }] = useUrlSearchParams();
const [query, setQuery] = useState(urlQuery);
const [limit, setLimit] = useState(10);
const [page, setPage] = useState(1);
Expand Down
22 changes: 11 additions & 11 deletions apps/web/src/components/paginated.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { useScrollIntoView } from "@mantine/hooks";
import { pathOr } from "ramda";
import { FC, ReactNode, useCallback, useEffect, useState } from "react";
import { limitBounds, usePaginationParams } from "../hooks/usePaginationParams";
import { limitBounds, useUrlSearchParams } from "../hooks/useUrlSearchParams";

export const perPageList = Array.from({ length: 3 }).map((_, index) => {
const key = ((index + 1) * 10).toString() as keyof typeof limitBounds;
Expand All @@ -27,7 +27,7 @@ export interface PaginatedProps extends Omit<StackProps, "onChange"> {

const Paginated: FC<PaginatedProps> = (props) => {
const { children, totalCount, fetching, onChange, ...restProps } = props;
const [{ limit, page }, updateParams] = usePaginationParams();
const [{ limit, page, query }, updateParams] = useUrlSearchParams();
const totalPages = Math.ceil(
totalCount === undefined || totalCount === 0 ? 1 : totalCount / limit,
);
Expand All @@ -43,36 +43,36 @@ const Paginated: FC<PaginatedProps> = (props) => {

const onChangeTopPagination = useCallback(
(pageN: number) => {
updateParams(pageN, limit);
updateParams(pageN, limit, query);
},
[limit, updateParams],
[limit, query, updateParams],
);

const onChangeBottomPagination = useCallback(
(pageN: number) => {
updateParams(pageN, limit);
updateParams(pageN, limit, query);
scrollIntoView({ alignment: "center" });
},
[limit, scrollIntoView, updateParams],
[limit, query, scrollIntoView, updateParams],
);

const onChangeLimit = useCallback(
(val: string | null) => {
const entry = val ?? limit;
const nextLimit = pathOr(limit, [entry], limitBounds);
updateParams(page, nextLimit);
updateParams(page, nextLimit, query);
},
[limit, page, updateParams],
[limit, page, query, updateParams],
);

useEffect(() => {
if (!fetching && page > totalPages) {
updateParams(totalPages, limit);
updateParams(totalPages, limit, query);
}
}, [limit, page, fetching, totalPages, updateParams]);
}, [limit, page, fetching, totalPages, updateParams, query]);

useEffect(() => {
setActivePage((activePage) =>
setActivePage((activePage: number) =>
activePage !== page ? page : activePage,
);
}, [page]);
Expand Down
32 changes: 21 additions & 11 deletions apps/web/src/components/search.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
import { Box, Loader, TextInput } from "@mantine/core";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { CiSearch } from "react-icons/ci";
import { useQueryParams } from "../hooks/useQueryParams";
import { useUrlSearchParams } from "../hooks/useUrlSearchParams";

export type SearchProps = {
isLoading: boolean;
onChange: (query: string) => void;
};

const Search: React.FC<SearchProps> = ({ onChange, isLoading }) => {
const { query, updateQueryParams } = useQueryParams();
const [keyword, setKeyword] = useState<string>(query);
const [{ limit, page, query }, updateParams] = useUrlSearchParams();
const [search, setSearch] = useState<string>(query);
const lastSearch = useRef(search);

useEffect(() => {
updateQueryParams(keyword);
onChange(keyword);
}, [query, onChange, keyword, updateQueryParams]);
if (lastSearch.current !== query) {
Copy link
Collaborator

@brunomenezes brunomenezes Dec 19, 2024

Choose a reason for hiding this comment

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

I wonder if that useEffect is necessary and if the logic ever runs because of how the onSearch callback is defined below. I believe the effect is fired as expected, but I guess that if is never evaluated to true.

cc: @nevendyulgerov

setSearch(query);
onChange(query);
lastSearch.current = query;
}
}, [query, onChange]);

const onSearch = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setKeyword(event.target.value);
const nextSearch = event.target.value;
lastSearch.current = nextSearch;

setSearch(nextSearch);
updateParams(page, limit, nextSearch);
onChange(nextSearch);
},
[],
[limit, page, onChange, updateParams],
);

return (
Expand All @@ -29,14 +39,14 @@ const Search: React.FC<SearchProps> = ({ onChange, isLoading }) => {
placeholder="Search by Address / Txn Hash / Index"
leftSection={<CiSearch />}
rightSection={
keyword &&
search &&
isLoading && (
<Loader size={"xs"} aria-label="loader-input" />
)
}
size="md"
data-testid="search-input"
value={keyword}
value={search}
onChange={onSearch}
/>
</Box>
Expand Down
33 changes: 0 additions & 33 deletions apps/web/src/hooks/useQueryParams.tsx

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { pathOr } from "ramda";
import { useCallback, useMemo } from "react";
import { useQueryParams } from "./useQueryParams";

export const limitBounds = {
"10": 10,
Expand All @@ -12,35 +11,38 @@ export const limitBounds = {
export type LimitBound = (typeof limitBounds)[keyof typeof limitBounds];

export type UsePaginationReturn = [
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think you forgot to rename the Interface to also match the new hook's name

cc: @nevendyulgerov

{ limit: LimitBound; page: number },
(page: number, limit: LimitBound) => void,
{ limit: LimitBound; page: number; query: string },
(page: number, limit: LimitBound, query: string) => void,
];

export const usePaginationParams = (): UsePaginationReturn => {
export const useUrlSearchParams = (): UsePaginationReturn => {
const searchParams = useSearchParams();
const router = useRouter();
const pathName = usePathname();
const { query } = useQueryParams();
const urlSearchParams = new URLSearchParams(searchParams);
const pg = parseInt(urlSearchParams.get("pg") ?? "");
const lt = urlSearchParams.get("lt") ?? limitBounds[10];
const limit = pathOr(limitBounds[10], [lt], limitBounds);
const page = isNaN(pg) ? 1 : pg;
const query = urlSearchParams.get("query") ?? "";

const updateParams = useCallback(
(page: number, limit: number): void => {
(page: number, limit: number, query: string): void => {
const urlSearchParams = new URLSearchParams({
query: query.toString(),
pg: page.toString(),
lt: limit.toString(),
});

router.push(`${pathName}?${urlSearchParams.toString()}`, {
scroll: false,
});
},
[query, router, pathName],
[router, pathName],
);

return useMemo(
() => [{ page, limit }, updateParams],
[limit, page, updateParams],
() => [{ page, limit, query }, updateParams],
[page, limit, query, updateParams],
);
};
26 changes: 13 additions & 13 deletions apps/web/test/components/paginated.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ import {
import { useScrollIntoView } from "@mantine/hooks";
import { withMantineTheme } from "../utils/WithMantineTheme";
import Paginated from "../../src/components/paginated";
import { usePaginationParams } from "../../src/hooks/usePaginationParams";
import { useUrlSearchParams } from "../../src/hooks/useUrlSearchParams";
import { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";

vi.mock("next/navigation");
const usePathnameMock = vi.mocked(usePathname, true);
const useRouterMock = vi.mocked(useRouter, true);
const useSearchParamsMock = vi.mocked(useSearchParams, true);

vi.mock("../../src/hooks/usePaginationParams");
const usePaginationParamsMock = vi.mocked(usePaginationParams, true);
vi.mock("../../src/hooks/useUrlSearchParams");
const useUrlSearchParamsMock = vi.mocked(useUrlSearchParams, true);

vi.mock("@mantine/hooks");
const useScrollIntoViewMock = vi.mocked(useScrollIntoView, true);
Expand All @@ -40,8 +40,8 @@ describe("Paginated component", () => {
useSearchParamsMock.mockReturnValue(
new URLSearchParams() as unknown as ReadonlyURLSearchParams,
);
usePaginationParamsMock.mockReturnValue([
{ limit: 10, page: 1 },
useUrlSearchParamsMock.mockReturnValue([
{ limit: 10, page: 1, query: "" },
vi.fn(),
]);
useScrollIntoViewMock.mockReturnValue({
Expand Down Expand Up @@ -78,11 +78,11 @@ describe("Paginated component", () => {

it("should invoke updateParams function when top pagination prev page button is clicked", async () => {
const mockedUpdateParams = vi.fn();
usePaginationParamsMock.mockReturnValue([
{ limit: 10, page: 2 },
useUrlSearchParamsMock.mockReturnValue([
{ limit: 10, page: 2, query: "" },
mockedUpdateParams,
]);
const { container, rerender } = render(
const { container } = render(
<Component {...defaultProps} totalCount={20}>
Children
</Component>,
Expand All @@ -95,20 +95,20 @@ describe("Paginated component", () => {
) as HTMLButtonElement;

fireEvent.click(prevPageButton);
expect(mockedUpdateParams).toHaveBeenCalledWith(1, 10);
expect(mockedUpdateParams).toHaveBeenCalledWith(1, 10, "");
});

it("should invoke updateParams function when bottom pagination button is clicked", async () => {
const mockedUpdateParams = vi.fn();
usePaginationParamsMock.mockReturnValue([
{ limit: 10, page: 2 },
useUrlSearchParamsMock.mockReturnValue([
{ limit: 10, page: 2, query: "" },
mockedUpdateParams,
]);
const mockedScrollIntoView = vi.fn();
useScrollIntoViewMock.mockReturnValue({
scrollIntoView: mockedScrollIntoView,
} as any);
const { container, rerender } = render(
const { container } = render(
<Component {...defaultProps} totalCount={20}>
Children
</Component>,
Expand All @@ -124,7 +124,7 @@ describe("Paginated component", () => {
) as HTMLButtonElement;

fireEvent.click(prevPageButton);
expect(mockedUpdateParams).toHaveBeenCalledWith(1, 10);
expect(mockedUpdateParams).toHaveBeenCalledWith(1, 10, "");
expect(mockedScrollIntoView).toHaveBeenCalled();
});
});
Loading
Loading