Skip to content

Commit

Permalink
Add serch params for sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksandr-slobodian committed May 22, 2024
1 parent 04fc9e4 commit 14b5616
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions src/hooks/sort-list/useSortList.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import _orderBy from "lodash/orderBy";

type TSortDir = "asc" | "desc";
Expand All @@ -8,13 +8,40 @@ export function useSortList(
name: string,
direction: TSortDir = "desc"
) {
const [currentName, setCurrentName] = useState(name);
const [currentDerection, setCurrentDirection] = useState(direction);
const searchParams = new URLSearchParams(window.location.search);

const [currentName, setCurrentName] = useState(
searchParams.get("sort") || name
);
const [currentDerection, setCurrentDirection] = useState(
(searchParams.get("order") as TSortDir) || direction
);

const handleSort = (name: string, dir: TSortDir) => {
const url = new URL(window.location.href);

url.searchParams.set("sort", name);
url.searchParams.set("order", dir);

window.history.pushState(null, "", url);
setCurrentName(name);
setCurrentDirection(dir);
};

useEffect(() => {
const handleUrlChange = () => {
const searchParams = new URLSearchParams(window.location.search);
setCurrentName(searchParams.get("sort") || name);
setCurrentDirection((searchParams.get("order") as TSortDir) || direction);
};

window.addEventListener("popstate", handleUrlChange);

return () => {
window.removeEventListener("popstate", handleUrlChange);
};
}, []);

const sortedList = _orderBy(list, [currentName], [currentDerection]);

return {
Expand Down

0 comments on commit 14b5616

Please sign in to comment.